Home >Web Front-end >JS Tutorial >Draw an isosceles triangle with nearest perimeter using JavaScript

Draw an isosceles triangle with nearest perimeter using JavaScript

PHPz
PHPzforward
2023-09-06 18:57:081390browse

使用 JavaScript 绘制具有最近周长的等腰三角形

Approximate isosceles triangle

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.

Question

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]

Example

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));

Output

[ 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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete