What is GCD?

Greatest common divisor (GCD) is the largest number which is a divisor of both and . It’s commonly denoted by .

Algorithm

Originally, the Euclidean algorithm was formulated as follows: subtract the smaller number from the larger one until one of the numbers is zero. Indeed, if divides and , it also divides . On the other hand, if divides and , then it also divides , which means that the sets of the common divisors of and coincide.

Note that remains the larger number until is subtracted from it at least times. Therefore, to speed things up, is substituted with . Then the algorithm is formulated in an extremely simple way:

Implementation

def gcd(a, b):
    if b == 0: return a
 
    return gcd(b, a % b)

Time Complexity

The running time of the algorithm is estimated by Lamé’s theorem, which establishes a surprising connection between the Euclidean algorithm and the Fibonacci sequence:

If and for some , the Euclidean algorithm performs at most recursive calls.

Moreover, it is possible to show that the upper bound of this theorem is optimal. When and , will perform exactly recursive calls. In other words, consecutive Fibonacci numbers are the worst case input for Euclid’s algorithm.

Given that Fibonacci numbers grow exponentially, we get that the Euclidean algorithm works in .

Another way to estimate the complexity is to notice that for the case is at least times smaller than , so the larger number is reduced at least in half on each iteration of the algorithm.

Least common multiple

Calculating the least common multiple (commonly denoted LCM) can be reduced to calculating the GCD with the following simple formula:

Thus, LCM can be calculated using the Euclidean algorithm with the same time complexity:

A possible implementation, that cleverly avoids integer overflows by first dividing with the GCD, is given here:

def lcm(a, b):
    return a // gcd(a, b) * b

Resources

  1. Euclidean Algorithm - CP Algorithms