Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 <= perimeter; a++){
for(let b = a; b <= perimeter - a; b++){
for(let c = b; c <= perimeter - a - b; c++){
if(a + b + c !== perimeter){
continue;
};
if((a * a) + (b * b) === (c * c)){
res.push([a, b, c]);
};
};
};
};
return res;
};
console.log(findAllRight(perimeter));
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 < perimeter / 3; a++){
for(let b = a; b < (perimeter - a) / 2; b++){
const c = perimeter - a - b;
if(a * a + b * b === c * c){
res.push([a, b, c]);
}
}
}
return res;
};
console.log(findAllRightOptimized(120));
console.log(findAllRightOptimized(60));
[ [ 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 ? cto 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.
