How to calculate the greatest common divisor using js

藏色散人
Release: 2021-08-12 11:31:26
Original
4397 people have browsed it

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:

    
   
Copy after login

The result is:

How to calculate the greatest common divisor using js

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

Output:

How to calculate the greatest common divisor using js

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!

Related labels:
js
source:php.cn
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
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!