Sub topic 3
Why gcd(a, b) Equals gcd(b, a mod b)
Euclid's algorithm depends on one fact: replacing the pair (a, b) with (b, a mod b) does not change the greatest common divisor. This chapter states that fact precisely, proves it, tests it in code, and covers the conditions under which it holds. Once you understand why the identity is true, the algorithm in the later chapters follows almost directly.
This chapter assumes you already know:
- The definitions of divisibility and the GCD from the first chapter. "d divides n" (written d | n) means n = d·k for some integer k.
- Division with remainder from the previous chapter: for integers a and b with b > 0, there are unique integers q and r with a = q·b + r and 0 ≤ r < b.
- How to read short Python functions and follow a direct proof.
The Statement
For integers a and b with b ≠ 0:
gcd(a, b) = gcd(b, a mod b)
Here a mod b is the remainder r from dividing a by b. In words, the GCD of a and b equals the GCD of b and the remainder you get when you divide a by b.
The identity applies only when b ≠ 0, because a mod 0 is undefined. When b = 0 the algorithm stops instead of applying the identity, and gcd(a, 0) = |a| is its base case. A later chapter on zero and negative inputs covers that case.
The One Lemma You Need
The whole proof uses one small fact about divisibility.
Linear combination lemma. If d | x and d | y, then d | (m·x + n·y) for any integers m and n.
Proof: if d | x and d | y, then x = d·k and y = d·l for some integers k and l. So
m·x + n·y = m·d·k + n·d·l = d·(m·k + n·l).
The value m·k + n·l is an integer, so d divides m·x + n·y.
The name comes from the fact that m·x + n·y is a linear combination of x and y with integer coefficients. Any number that divides both x and y also divides every combination of this kind. Two cases of the lemma do the work in this chapter: d | (x − q·y) and d | (q·y + x).
The Proof: The Common Divisors Are the Same
Write r = a mod b, so that a = q·b + r for the quotient q. Equivalently, r = a − q·b.
The strategy is to prove something stronger than the identity. We show that (a, b) and (b, r) have exactly the same common divisors. If two sets are equal, their largest elements are equal, and that gives the GCD identity.
Direction 1: every common divisor of a and b divides r. Suppose d | a and d | b. Then r = a − q·b = 1·a + (−q)·b is a linear combination of a and b, so d | r by the lemma. Because d already divides b, d is a common divisor of b and r.
Direction 2: every common divisor of b and r divides a. Suppose d | b and d | r. Then a = q·b + r = q·b + 1·r is a linear combination of b and r, so d | a. Because d already divides b, d is a common divisor of a and b.
Each set is contained in the other, so the sets are equal:
{common divisors of a and b} = {common divisors of b and r}
Both sets are finite and non-empty. They contain 1, and they are finite because b ≠ 0 and every divisor of a nonzero number is at most its absolute value. Equal sets have the same maximum, so gcd(a, b) = gcd(b, r). ∎
A Concrete Check: 1071 and 462
Dividing 1071 by 462 gives 1071 = 2·462 + 147, so the identity says gcd(1071, 462) = gcd(462, 147). You can confirm this from the prime factorizations.
| Number | Factorization | Divisors that matter here |
|---|---|---|
| 1071 | 3² · 7 · 17 | contains 3 · 7 |
| 462 | 2 · 3 · 7 · 11 | contains 3 · 7 |
| 147 | 3 · 7² | contains 3 · 7 |
The common divisors of 1071 and 462 are {1, 3, 7, 21}. The common divisors of 462 and 147 are also {1, 3, 7, 21}. Both pairs have GCD 21, as the proof predicts.
Some divisors change from one pair to the other. The divisor 17 of 1071 is gone, and 147 gains a second factor of 7. The divisors that both numbers share stay exactly the same. That is why the proof compares sets of common divisors instead of the numbers themselves.
Testing the Identity in Code
Factorizations are only practical for small numbers. A brute-force test checks the stronger set-equality claim directly on thousands of random pairs.
import random
def common_divisors(a, b):
"""All positive d that divide both a and b (not both zero)."""
n = max(abs(a), abs(b))
return {d for d in range(1, n + 1) if a % d == 0 and b % d == 0}
def check(trials=300, seed=1):
rng = random.Random(seed)
for _ in range(trials):
a = rng.randint(1, 400)
b = rng.randint(1, 400)
q = rng.randint(-5, 5)
cd = common_divisors(a, b)
# The identity with the true remainder
assert cd == common_divisors(b, a % b), (a, b)
# The identity with an arbitrary multiple q subtracted
assert cd == common_divisors(b, a - q * b), (a, b, q)
print("all checks passed")
check()
print(common_divisors(1071, 462)) # {1, 3, 7, 21}
print(common_divisors(462, 1071 % 462)) # {1, 3, 7, 21}common_divisors(b, 0) returns all divisors of b, because 0 % d == 0 for every d. That matches the mathematics: every integer divides 0, so the common divisors of b and 0 are just the divisors of b.
The Quotient Does Not Matter
Look again at the proof. It never used 0 ≤ r < b, and it never used the fact that q is the quotient. It only used r = a − q·b for some integer q. So the stronger statement is:
gcd(a, b) = gcd(b, a − q·b) for every integer q.
The second assertion in the test checks exactly this. The choice of q then becomes a decision about efficiency, not about correctness:
| Choice of q | Resulting second value | Where you'll see it | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| q = 1 | a − b | Euclid's subtraction method (next chapter) | ||||
| q = ⌊a / b⌋ | a mod b, the smallest non-negative value | The standard algorithm | ||||
| q chosen so \ | a − q·b\ | ≤ \ | b\ | / 2 | least absolute remainder | A variant that can save steps |
Taking the true remainder makes the second value as small as it can be without going negative. Shrinking the numbers as fast as possible is what makes the algorithm fast. The chapter on Lamé's theorem quantifies how fast.
Common Misreadings
"The GCD is the remainder"
The identity does not say gcd(a, b) = a mod b. For a = 10 and b = 4, a mod b = 2, which happens to be the GCD. For a = 10 and b = 7, a mod b = 3, but gcd(10, 7) = 1. The identity only reduces the problem to a smaller pair, which you then have to keep reducing.
"You need a ≥ b"
The identity holds whatever order a and b are in. If 0 ≤ a < b, then a mod b = a, and the identity becomes gcd(a, b) = gcd(b, a). That just swaps the two values. So an implementation does not need to sort its inputs, because the first step sorts them for free.
"It works for b = 0"
It does not. a mod 0 raises an error in Python and is undefined behavior for integers in C. Every correct implementation checks b ≠ 0 before it applies the identity.
Negative operands and the sign of `%`
Programming languages disagree about the sign of a remainder. Python's % takes the sign of the divisor, so -7 % 3 == 2. C, C++, Java, and JavaScript truncate toward zero, so -7 % 3 == -1.
print(-7 % 3) # 2 (Python: floored division)
print(7 % -3) # -2
import math
print(math.fmod(-7, 3)) # -1.0 (C-style truncation, as a float)Both conventions give a value of the form a − q·b for some integer q. By the stronger statement above, the set of common divisors is preserved either way. The only risk is that the final answer may come out negative, for example −3 instead of 3. Taking absolute values fixes that, and the edge-cases chapter shows where to put them.
Why the Stronger Statement Is Worth Keeping
Proving that the sets of common divisors are equal, and not only that their maximums are equal, gives you more than the identity.
- It survives every step. Each step of the algorithm keeps the same set of common divisors. When the pair reaches (g, 0), that set is the set of divisors of g. So every common divisor of the original a and b divides g, not just is at most g. This is the property the correctness proof builds on.
- It explains the extended algorithm. Each new remainder is a − q·b, a linear combination of the previous two values. By induction, every remainder is an integer combination of the original a and b. The extended Euclidean algorithm keeps track of those combination coefficients.
- It applies beyond integers. The proof uses only addition, multiplication, and division with remainder. The same argument works for polynomials over a field, which is why there is a polynomial GCD algorithm.
The chain in this diagram is the algorithm itself. Its implementation and its termination proof come in later chapters. This chapter's job was to show that every arrow keeps the answer the same.
Exercise
Using only the linear combination lemma, prove that gcd(a, b) = gcd(a + b, b) for integers a and b that are not both zero.
Show answer
If d | a and d | b, then d | (1·a + 1·b) = a + b, so d is a common divisor of a + b and b. Conversely, if d | (a + b) and d | b, then d | (1·(a + b) + (−1)·b) = a, so d is a common divisor of a and b. The two sets of common divisors are equal, so their maximums are equal. This is the stronger statement with q = −1.
Exercise
Someone claims gcd(a, b) = gcd(b, a·b mod b + 1). Without proving anything, explain why this must be wrong, and give a counterexample.
Show answer
a·b mod b is always 0, so the right-hand side is gcd(b, 1) = 1 for every input. That would make every GCD equal 1. Counterexample: gcd(4, 6) = 2, but the formula gives 1. The value 0 + 1 is not of the form a − q·b, so the lemma does not apply.
Exercise
In C, -20 % 6 evaluates to -2, while in Python it evaluates to 4. Show that gcd(6, -2) and gcd(6, 4) are both equal to gcd(-20, 6), and explain why both remainders are valid for the identity.
Show answer
The positive common divisors of -20 and 6 are {1, 2}, so gcd(-20, 6) = 2. The common divisors of 6 and -2 are {1, 2}, and the common divisors of 6 and 4 are {1, 2}, so both GCDs are 2. Both remainders have the form a − q·b: -2 = -20 − (−3)·6 and 4 = -20 − (−4)·6. The identity holds for every integer q, so both are valid.
Exercise
Modify the check() function so it also confirms that, for random a and b, every common divisor of a and b divides gcd(a, b) as computed by math.gcd. What property from this chapter does this test reflect?
Show answer
Inside the loop, add: g = math.gcd(a, b); assert all(g % d == 0 for d in cd), and add import math at the top. The test reflects the stronger set-equality statement. Every step keeps the same set of common divisors, and the final pair (g, 0) has the divisors of g as its common divisors, so every common divisor of a and b divides g.