The Euclidian algorithm

The Euclidian algorithm is a simple algorithm to compute the greatest common divisor (or simply gcd) of two numbers. While the Euclidian algorithm is very simple, it is also very efficient.

Theory

The greatest common divisor of two numbers is the greatest number that divides both numbers. The Euclidian algorithm is based on two simple observations:

where reduces modulo to some number

When we assume that , we can use the second step to reduce the problem to computing the gcd of two numbers, where one of the numbers is smaller.

Implementation

Usually, we have a wrapper function which swaps the arguments if we have , and then calls some helper function which assumes that :

def gcd(a, b):
if (a < b): return gcd_helper(b, a)
  else: return gcd_helper(a, b)

Then the implementation can be done recursively in an elegant way:

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

Note that gcd_helper assumes that . The gcd function ensures this the first time that gcd_helper is called. For every call of gcd_helper to itself, we can use that to see that this condition is fulfilled.

If we call the values of and with which the gcd_helper function is first called and , and the values in the next call and , and so on, we obtain:

which motivates the following implementation:

def gcd_helper(a, b):
	while b != 0:
		(a, b) = (b, a % b)
	return a

Note that gcd(0, 0) is not defined, but this implementation will return 0. Calling gcd with negative arguments might give a negative result. Depending on your application, you might want to fix this. For example, you might want to throw an error when gcd(0, 0) is called, or call gcd_helper with the absolute value of the arguments in the gcd function.

Analysis

Take the Fibonacci sequence

which is defined as , and for .

When we use the Euclidian algorithm to compute , it will finish after steps. If we use the Euclidian algorithm to compute with and , the Euclidian algorithm will terminate in less than steps. So, two successive Fibonacci numbers are the worst case input for the Euclidian algorithm, in some sense.

This is a consequence of the fact that we have . So in this case, the modulo operator will subtract from only once, which is the worst case.

Since the Fibonacci sequence satisfies

we can deduce that the number of steps that the Euclidian algorithm will take is bounded by .