GCD with the Euclidean algorithm

Open on YouTube

1 The largest number that divides both

The fraction 78/30 is easier to read as 13/5. To get there, we divide the top and the bottom by the same number, and we want the largest number that divides both. That number is their greatest common divisor, or GCD.

The numbers that divide 78 are 1, 2, 3, 6, 13, 26, 39 and 78. The numbers that divide 30 are 1, 2, 3, 5, 6, 10, 15 and 30. The two lists share 1, 2, 3 and 6, so gcd(78, 30) = 6, and 78/30 = 13/5.

Lists work by hand for small numbers. The problems in this part of the roadmap give numbers up to 10¹⁵, so we need a method that stays fast at that size.

2 The slow way: try every number

The GCD cannot be larger than the smaller number. So the direct method starts at min(a, b) and counts down. The first number that divides both is the largest such number, and we return it.

for d from min(a, b) down to 1
    if a % d == 0 and b % d == 0
        return d

For 78 and 30, it tries 30, 29, 28 and so on, and stops at 6 after 25 tries.

The loop always ends, because 1 divides every number. The trouble is its length. When the two numbers share nothing but 1, it tries every value from min(a, b) down to 1, so it is O(min(a, b)). At 10¹⁵ that is around 10¹⁵ steps. At about 10⁸ steps a second, it gets Time Limit Exceeded (TLE).

3 Why gcd(a, b) = gcd(b, a % b)

The fast method is the Euclidean algorithm. It rests on one fact:

gcd(a, b) = gcd(b, a % b)

Here a % b is the remainder when we divide a by b. For our pair, the fact says gcd(78, 30) = gcd(30, 18). The new pair is smaller, and it has the same GCD.

The reason takes two steps:

  • A common divisor survives a subtraction. If d divides both a and b, then a = d × x and b = d × y. So a − b = d × (x − y), and d divides a − b too.
  • A remainder is repeated subtraction. a % b is what is left of a after we take b away as many times as it fits. Each subtraction keeps d as a divisor, so d divides a % b.
3030180306078
78 is two 30s and 18 left over. A number that divides 78 and 30 also divides the 18

The argument also works the other way round. A number that divides b and a % b also divides a, because a is a few copies of b plus a % b.

So (78, 30) and (30, 18) have exactly the same common divisors: 1, 2, 3 and 6. Their largest common divisor is the same too.

4 Tracing 78 and 30

We apply the fact again and again. Each step replaces the pair (a, b) with (b, a % b):

Stepabremainder = a % b
1783018
2301812
318126
41260
560—

The loop stops when b reaches 0. Then a holds the answer, 6. The slow way needed 25 tries, and this needs 4 remainders.

Stopping at b = 0 is right because every number divides 0, as 0 = d × 0. So the common divisors of 6 and 0 are just the divisors of 6, and the largest of them is 6. In short, gcd(a, 0) = a.

Every language writes the same loop. The numbers reach 10¹⁵, so we use 64-bit integers: long long, long, int64 and i64.

The fact also reads as a function that calls itself: gcd(a, b) returns gcd(b, a % b), and gcd(a, 0) returns a. The next lesson, on recursion and the call stack, shows how such a function runs.

5 Why it takes about log n steps

Each step costs a few operations, so the cost is the number of steps. The numbers fall fast. Two steps later, the first number is always less than half of what it was:

  • b is at most half of a. The remainder is smaller than b, so it is smaller than half of a.
  • b is more than half of a. Then b fits into a only once. The remainder is a − b, and that is less than half of a.

The trace shows it. Two steps after 78 comes 18, two steps after 30 comes 12, and two steps after 18 comes 6.

783018126
The value of a at each step. Each blue bar is less than half of the blue bar before it

A number up to 10¹⁵ halves about 50 times before it reaches 1. So the loop runs at most about 100 times. The time is O(log n), with n the smaller of the two numbers. The space is O(1): only a, b and remainder.

Slow way10¹⁵Euclidean100about 1 second
Steps for numbers up to 10¹⁵, on a scale where each mark is ten times the last

6 LCM from the GCD

The least common multiple, or LCM, is the smallest number that both a and b divide. It tells us, for example, when two repeating events next happen together. The GCD gives it directly:

lcm(a, b) = a / gcd(a, b) × b

For our pair, 78 = 6 × 13 and 30 = 6 × 5. A multiple of 78 must contain 6 × 13, and a multiple of 30 must contain 6 × 5. 13 and 5 share no divisor except 1, so the smallest number with both is 6 × 13 × 5 = 390. The formula gives the same: 78 / 6 = 13, and 13 × 30 = 390.

The same formula is often written a × b / gcd(a, b). On paper the two are equal. In code, the second one overflows:

a = 10^15, b = 10^15
a * b / gcd(a, b)
    a * b is 10^30: overflow
a / gcd(a, b) * b
    10^15 / 10^15 * 10^15 = 10^15

A 64-bit integer holds up to about 9.2 × 10¹⁸. The product overflows before the division can bring it back down, even though the LCM itself fits. In Java, the first line returns 5076 instead of 10¹⁵.

Dividing first is safe. gcd(a, b) divides a exactly, so a / gcd(a, b) is a whole number, and no step is ever larger than the answer.

7 Zero and the order of a and b

  • a smaller than b. We do not need to swap them. For gcd(30, 78), the first step finds 30 % 78 = 30, so the pair becomes (78, 30). From there, the trace above carries on, one step longer.
  • One number is 0. gcd(12, 0) is 12, and the loop returns at once. gcd(0, 12) takes one step to become (12, 0). The slow way breaks here: it starts at min(0, 12) = 0, so its loop never runs.
  • Both are 0. Every number divides 0, so no largest common divisor exists. By convention gcd(0, 0) is 0, and the loop returns 0.
  • LCM with 0. lcm(0, 0) divides by gcd(0, 0) = 0, which is a Runtime Error. When a problem allows 0, we return 0 for the LCM before dividing.

8 Built-ins and when to use it

Some languages have the GCD built in:

C++

Built in. std::gcd and std::lcm, in <numeric> (C++17).

Built in. math.gcd, and math.lcm from Python 3.9.

None for int or long. Only BigInteger has a GCD.

None for int or long. Only BigInteger has a GCD.

None for int. Only big.Int has a GCD.

None.

None in the standard library.

Without a built-in, we write the loop ourselves. It is a few lines, and in an interview it shows we know why it works.

A problem needs these ideas when its numbers have to fit together:

  • "Largest that divides both", or a fraction to simplify. This is the GCD.
  • "Smallest that both divide", or two cycles lining up. This is the LCM.
  • A whole array. gcd(a, b, c) = gcd(gcd(a, b), c), so we carry one running GCD across the array.

The habit to keep: when a formula multiplies and then divides, look for a way to divide first. Then no step grows past the answer.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.