← Lessons

quiz vs the machine

Silver1100

Algorithms

The Greatest Common Divisor by Euclid

How repeated remainders quickly reduce two numbers to their largest shared divisor.

4 min read · intro · beat Silver to climb

The oldest nontrivial algorithm

The greatest common divisor of two integers is the largest number dividing both. Euclid's method computes it without factoring, using a simple insight about remainders.

The key fact

Any number that divides both a and b also divides their remainder when a is divided by b. So the common divisors of a and b are exactly the common divisors of b and that remainder. Replacing the larger number by the remainder shrinks the problem while preserving the answer.

The procedure

  • Given a and b, compute the remainder of a divided by b.
  • Replace a with b and b with that remainder.
  • Repeat until the remainder is zero.
  • The last nonzero value is the greatest common divisor.

Because the remainder is always smaller than the divisor, the numbers fall rapidly. The number of steps grows only with the number of digits, so even huge inputs finish quickly. Consecutive Fibonacci numbers are the worst case.

Key idea

Euclid replaces the larger number with the remainder repeatedly; common divisors are preserved, and when the remainder hits zero the last value is the greatest common divisor.

Check yourself

Answer to earn rating on the learn ladder.

1. Why does replacing a with b and b with the remainder preserve the answer?

2. When does Euclid's algorithm stop?