Greatest Common Divisor and Least Common Multiple

Finds the greatest common divisor of two integers with the Euclidean algorithm, and the least common multiple as the product ÷ the GCD.

For two positive integers, the greatest common divisor (GCD) is the largest number that divides both, and the least common multiple (LCM) is the smallest number that both divide into.

The GCD comes from the Euclidean algorithm: divide the larger by the smaller, replace the pair with the divisor and the remainder, and repeat until the remainder is 0. The last value left is the GCD. It is far quicker than listing every divisor of both numbers.

Once you have the GCD, the LCM follows immediately.

lcm(a,b)=a×bgcd(a,b)\mathrm{lcm}(a, b) = \dfrac{a \times b}{\gcd(a, b)}

Example

Take a=12a = 12 and b=18b = 18. The algorithm runs:

The remainder has reached zero, so the GCD is 6. The LCM is then

12×186=2166=36\dfrac{12 \times 18}{6} = \dfrac{216}{6} = 36

Notes