Before starting this article, I would like to ask if you still remember what is the greatest common divisor? In fact, it refers to the largest common divisor of two or more integers. So today I will introduce to you how to calculate the greatest common divisor through a javascript program.
However, I still want to introduce the simple concept of the greatest common divisor here:
→The greatest common factor, also known as the greatest common divisor, is also called the greatest common divisor. The greatest common factor is the largest divisor shared by two or more integers. For example, the greatest common divisor of a and b is recorded as (a, b). Similarly, the greatest common divisor of a, b, c is recorded as (a, b, c). Then the greatest common divisor of multiple integers is also Same mark. In fact, there are many methods to find the greatest common divisor. Common ones include prime factorization method, short division method, euclidean division method and phase-changing subtraction method. The concept corresponding to the greatest common divisor is the least common multiple. The least common multiple of a and b is recorded as [a, b] (I won’t go into too much introduction here).
Let’s get straight to the point.
The specific question is: Please write a JavaScript program to calculate the greatest common divisor of two positive integers.
Then we go directly to the code:
<!DOCTYPE HTML> <html> <head> <script> var a = 2154; var b = 458; var gcd; while (a!=b) { if (a>b) { a = a -b; } else { b = b - a; } } gcd = a; console.log(gcd); </script> </head> <body> </body> </html>
The result is:
In the above code, we randomly gave two positive integers, They are 2154 and 458 respectively. It is obvious that the two greatest common divisors are 2.
Of course, replace it with another more obvious number:
var a = 25; var b = 75; var gcd; while (a!=b) { if (a>b) { a = a -b; } else { b = b - a; } } gcd = a; console.log(gcd);
Output:
The greatest common divisor of 25 and 75 is 25.
Finally, I would like to recommend "JavaScript Basics Tutorial" ~ Welcome everyone to learn ~
The above is the detailed content of How to calculate the greatest common divisor using js. For more information, please follow other related articles on the PHP Chinese website!