Home > Web Front-end > JS Tutorial > body text

Draw an isosceles triangle with nearest perimeter using JavaScript

PHPz
Release: 2023-09-06 18:57:08
forward
1365 people have browsed it

使用 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));
Copy after login

Output

[ 105, 104, 181 ]
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!