All right triangles with specified perimeter in JavaScript

We are required to write a JavaScript function that takes in a number that specifies the perimeter for a triangle. Our function should return an array of all the right triangle side triplets whose perimeter matches the specified input.

Understanding Right Triangles

A right triangle satisfies the Pythagorean theorem: a² + b² = c², where c is the hypotenuse (longest side). For a given perimeter P, we need a + b + c = P.

Algorithm Approach

We use three nested loops to check all possible combinations of triangle sides. For each triplet, we verify:

  • The sum equals the specified perimeter
  • The triplet satisfies the Pythagorean theorem

Implementation

const perimeter = 120;
const findAllRight = (perimeter = 1) => {
   const res = [];
   for(let a = 1; a 

Output

[
  [ 20, 48, 52 ],
  [ 24, 45, 51 ],
  [ 30, 40, 50 ]
]

Optimized Version

We can improve efficiency by calculating the third side instead of using a third loop:

const findAllRightOptimized = (perimeter) => {
   const res = [];
   for(let a = 1; a 

[ [ 20, 48, 52 ], [ 24, 45, 51 ], [ 30, 40, 50 ] ]
[ [ 10, 24, 26 ], [ 12, 21, 25 ], [ 15, 20, 25 ] ]

Key Points

  • The algorithm checks all possible combinations systematically
  • We ensure a ? b ? c to avoid duplicate triplets
  • The optimized version reduces time complexity by eliminating one loop
  • Results are returned as arrays of [a, b, c] triplets

Conclusion

This solution efficiently finds all right triangles with a specified perimeter using the Pythagorean theorem. The optimized approach reduces computational overhead while maintaining accuracy.

Updated on: 2026-03-15T23:19:00+05:30

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements