JS Find the greatest common divisor and greatest common multiple of two numbers

1. Greatest common divisor

First of all, you have to know how to find the greatest common divisor in mathematics. I do n’t know. It ’s too embarrassing. The teacher has only taught to compare divisors. . . .

The method of finding the greatest common divisor in mathematics is "toggle division", which is to divide one number by another (no need to know the size), take the remainder, divide the dividend by the remainder, then take the remainder, and divide by the new dividend Take the remainder with the new remainder until the remainder is 0, and the last dividend is the greatest common divisor

Knowing this, the code is simple

function gcd(  n,  m ){ 
    if( m == 0 ) return n; 
    return gcd( m, n % m ); 
} 
gcd(12,30)  // 6

2.Least common multiple

The first thing to know is the relationship between the least common multiple and the greatest common divisor: the least common multiple = multiplying the two numbers and dividing by the greatest common divisor

So knowing the greatest common divisor, the least common multiple code is no longer needed

 

Guess you like

Origin www.cnblogs.com/zhujunislucky/p/12674009.html