Find the greatest common divisor of two numbers
The greatest common factor, also known as the greatest common divisor, the greatest common factor, refers to two or more integers common divisor of the largest one. List all the factors of one number, and then start with the largest of those factors to determine whether the other number is divisible. For example,8 and 12, you could list all the factors of 8, 1,2,4,8, and then go into 12 from 8, obviously, and go into 12 at 4. And notice, at the end of each function, you can check it.
Method 1: Cyclic mod method:
<script>
// loop remainder method
// Encapsulate a function to find the greatest common factor. The arguments a and b are the numbers of the two factors
function isyinzi(a, b) {
for (var i = a; i >= 1; i--) {
// Find the factor of a number
if (a % i == 0) {
// Find the common factor in the first factor, starting from the largest to the smallest.
if (b % i == 0) {
// Return the greatest common factor
returni; }}}}console.log(isyinzi(3.12))// Call the function
</script>
Copy the code
Method two: toss and turn division, write recursively (Euclidean algorithm)
<script>
// Encapsulate a function to find the greatest common divisor of two numbers. The arguments a and b are two numbers
function isyinzi(a, b) {
// Define an intermediate variable to swap a,b, a must be the largest of the two numbers
var z = 0;
if (a < b) {
z = a;
a = b;
b = z;
}
// The Euclidean algorithm is expressed recursively. The idea is that, to name a few,
A /b=c..... D the value of A the second time is the value of b the first time, b
// is the value of d for the first time, and so on, until d is 0
function isdigui() {
if(a % b ! =0) {
return a % b
} else return b
a = b;
return a % isdigui() // Call yourself recursively until the judgment condition is reached
}
return isdigui()
}
console.log(isyinzi(12.8)) // Call the function
</script>
Copy the code
Ultimate edition: Think the same. Essentially the same
function isgy(a, b) {
return a % b == 0 ? b : isgy(b, a % b)
}
console.log(isgy(4.8))
Copy the code
The results are as follows: