JavaScript 中具有指定周长所有直角三角形
问题
我们需要编写一个 JavaScript 函数,该函数接受一个指定三角形周长的数字。我们的函数应该返回周长与输入相同的三角形三元组的数组。
示例
以下为代码 −
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 = a; c <= a + b; c++){ if(a + b + c !== perimeter){ continue; }; if((a * 2) + (b * 2) === (c * 2)){ res.push([a, b, c]); }; }; }; }; return res; }; console.log(findAllRight(perimeter));
输出
以下为控制台输出 −
[ [ 1, 59, 60 ], [ 2, 58, 60 ], [ 3, 57, 60 ], [ 4, 56, 60 ], [ 5, 55, 60 ], [ 6, 54, 60 ], [ 7, 53, 60 ], [ 8, 52, 60 ], [ 9, 51, 60 ], [ 10, 50, 60 ], [ 11, 49, 60 ], [ 12, 48, 60 ], [ 13, 47, 60 ], [ 14, 46, 60 ], [ 15, 45, 60 ], [ 16, 44, 60 ], [ 17, 43, 60 ], [ 18, 42, 60 ], [ 19, 41, 60 ], [ 20, 40, 60 ], [ 21, 39, 60 ], [ 22, 38, 60 ], [ 23, 37, 60 ], [ 24, 36, 60 ], [ 25, 35, 60 ], [ 26, 34, 60 ], [ 27, 33, 60 ], [ 28, 32, 60 ], [ 29, 31, 60 ], [ 30, 30, 60 ] ]
广告