Home >Web Front-end >JS Tutorial >Draw an isosceles triangle with nearest perimeter using JavaScript
Approximate isosceles integer triangle is a triangle in which all side lengths are integers, and the two sides are almost equal, and their absolute difference is 1 unit of length.
We need to write a JavaScript function that accepts a number that specifies the perimeter of a triangle.
Our function should find an approximate isosceles triangle with such dimensions that the perimeter is closest to the input perimeter.
For example, if the required perimeter is 500,
The closest approximate isosceles triangle with perimeter would be - [105, 104, 181]
The following is the code-
Real-time demonstration
const perimeter = 500; const almostIsosceles = (perimeter = 0) => { let a = perimeter; for(; a > 0; a--){ for(let b = perimeter; b > 0; b--){ for(let c = perimeter; c > 0; c--){ if(a + b + c > perimeter || a !== b + 1 || (Math.pow(a, 3) - Math.pow(b, 3) !== Math.pow(c, 2))){ continue; }; return [a, b, c]; }; }; }; return []; }; console.log(almostIsosceles(perimeter));
[ 105, 104, 181 ]
The above is the detailed content of Draw an isosceles triangle with nearest perimeter using JavaScript. For more information, please follow other related articles on the PHP Chinese website!