Greatest Common Divisor

Explore the efficiency of Euclid’s algorithm in finding the greatest common divisors.

In this section, we will explain how to find the greatest common divisor of two integers aa and bb, a task that we used to factor NN back in The RSA Algorithm. Of course, you could always use “brute force” methods and first find all the divisors of the first integer—looking for integers that divide a with no remainder. Then, do the same for bb. Then, look at those divisors to find the divisors that are common to both and select from that subset the one that is the greatest. This works fine for relatively small numbers. But it takes a long time for larger numbers.

A more efficient way makes use of what is called Euclid’s algorithm (or the Euclidean algorithm), which was written up more than 2,000 years ago in Euclid’s famous book Elements. Many authors claim that this algorithm is the oldest known algorithm, but there is no historical evidence that Euclid himself invented it. What is important is that he made it readily available to subsequent generations of mathematicians. As we mentioned before, greatest-common-divisor functions are available in most programming languages and spreadsheets.

Here is how the algorithm works:

  1. Let aa be the larger of the two integers, aa and bb. Then, find the remainder r1r_1 from dividing aa by bb. If the remainder is 00, then bb is the greatest common divisor of aa and bb. If it is not, go to step 2.

  2. Divide bb by r1r_1 to find the remainder r2r_2. If r2r_2 is not equal to 00, proceed to step 3.

  3. Divide r1r_1 by r2r_2 to find a new remainder r3r_3.

  4. Continue these steps until the remainder is 00. The next-to-last remainder (the one that is non-zero) is the largest common divisor of aa and bb.

Get hands-on with 1400+ tech skills courses.