Sub topic 5
The Algorithm: Tracing and Implementing It
Earlier chapters proved the identity gcd(a, b) = gcd(b, a mod b) and showed Euclid's slower subtraction method. This chapter turns that identity into a working procedure. You will trace it by hand, write it in Python in iterative and recursive forms, and learn the mistakes people usually make when they code it.
This chapter assumes you can:
- read Python functions that use
whileloops and recursion, - use the
//(integer division) and%(remainder) operators, - follow the invariant gcd(a, b) = gcd(b, a mod b) from the earlier chapter.
Zero and negative inputs get a full chapter of their own next. The formal termination proof and the step-count bound come after that. Here we focus on the mechanics.
The Procedure in One Sentence
Euclid's algorithm repeats one step: replace the pair (a, b) with (b, a mod b), and stop when the second number becomes zero. The first number at that point is the GCD.
Two facts make this work:
- The invariant. Each replacement keeps the GCD of the pair the same, because gcd(a, b) = gcd(b, a mod b).
- The base case. gcd(a, 0) = a for any a ≥ 0, because every integer divides 0, so the common divisors of a and 0 are exactly the divisors of a.
The remainder a mod b always satisfies 0 ≤ a mod b < b, so the second number shrinks on every step. A strictly decreasing sequence of non-negative integers must reach zero, and when it does, the base case gives the answer.
Tracing by Hand
Tracing means writing each division as an equation a = q·b + r, where q is the quotient and r is the remainder. The divisor and remainder of one line become the dividend and divisor of the next.
Example: gcd(1071, 462)
| Step | a | b | Equation | q | r = a mod b |
|---|---|---|---|---|---|
| 1 | 1071 | 462 | 1071 = 2 · 462 + 147 | 2 | 147 |
| 2 | 462 | 147 | 462 = 3 · 147 + 21 | 3 | 21 |
| 3 | 147 | 21 | 147 = 7 · 21 + 0 | 7 | 0 |
| end | 21 | 0 | b is zero, stop |
The result is 21. You can check it: 1071 = 21 · 51 and 462 = 21 · 22. Since 51 = 3 · 17 and 22 = 2 · 11 share no common factor, 21 really is the greatest common divisor.
The invariant gives a chain of equal values:
gcd(1071, 462) = gcd(462, 147) = gcd(147, 21) = gcd(21, 0) = 21.
Example: gcd(48, 18)
| Step | a | b | Equation | r |
|---|---|---|---|---|
| 1 | 48 | 18 | 48 = 2 · 18 + 12 | 12 |
| 2 | 18 | 12 | 18 = 1 · 12 + 6 | 6 |
| 3 | 12 | 6 | 12 = 2 · 6 + 0 | 0 |
| end | 6 | 0 | stop |
The result is 6.
What Happens When a < b
You do not need to sort the inputs. If a < b, then a mod b = a, so the first step just swaps the pair:
| Step | a | b | Equation | r |
|---|---|---|---|---|
| 1 | 18 | 48 | 18 = 0 · 48 + 18 | 18 |
| 2 | 48 | 18 | continues as above |
This costs one extra step and nothing else. Code that sorts the inputs first gains nothing.
The Iterative Implementation
The loop form matches the flowchart directly.
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
print(gcd(1071, 462)) # 21
print(gcd(48, 18)) # 6
print(gcd(18, 48)) # 6Some notes on the design:
absmakes the function safe for negative inputs. The next chapter explains why the GCD is defined as non-negative and what Python's%does with negative operands.- The tuple assignment
a, b = b, a % bevaluates both right-hand expressions before it assigns either name. This detail matters, as the section on bugs shows. - The loop condition
b != 0is the base case test. When it fails,aholds the answer. - The function uses constant extra memory. It only ever stores two numbers.
Instrumenting the Loop
To check your hand traces, have the function record each division:
def gcd_trace(a, b):
a, b = abs(a), abs(b)
steps = []
while b != 0:
q, r = divmod(a, b)
steps.append((a, b, q, r))
a, b = b, r
return a, steps
result, steps = gcd_trace(1071, 462)
for a, b, q, r in steps:
print(f"{a} = {q} * {b} + {r}")
print("gcd =", result)Output:
1071 = 2 * 462 + 147
462 = 3 * 147 + 21
147 = 7 * 21 + 0
gcd = 21divmod(a, b) returns the quotient and remainder together. The plain GCD throws the quotients away, but the extended algorithm in a later chapter needs them.
The Recursive Implementation
The recursive form is the invariant and the base case written as code:
def gcd_recursive(a, b):
if b == 0:
return abs(a)
return gcd_recursive(b, a % b)
print(gcd_recursive(48, 18)) # 6
print(gcd_recursive(1071, 462)) # 21Each call does one step, so the call stack for gcd_recursive(1071, 462) looks like this:
gcd_recursive(1071, 462)
gcd_recursive(462, 147)
gcd_recursive(147, 21)
gcd_recursive(21, 0) -> returns 21The recursive call is the last thing the function does, which makes it a tail call. Some languages, such as Scheme, compile tail calls into loops. Python does not. Every step adds a stack frame, and the CPython default recursion limit is 1000 frames.
Comparing the Two Forms
| Property | Iterative | Recursive |
|---|---|---|
| Reads like the math | Fairly close | Exactly matches the invariant |
| Extra memory | Constant | One stack frame per step |
| Risk in Python | None | `RecursionError` on very long runs |
| Easy to instrument | Yes, append inside the loop | Yes, but traces come back through returns |
For everyday inputs the number of steps is small. Even 64-bit integers need fewer than 100 steps, so the recursive version works fine. A later chapter proves the step count grows with the number of digits and reaches its worst case on consecutive Fibonacci numbers. Python integers have no size limit, though, so you can build inputs that break the recursive version:
import sys
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
def gcd_recursive(a, b):
if b == 0:
return abs(a)
return gcd_recursive(b, a % b)
def fib_pair(n):
# Returns (F(n), F(n + 1)) with F(0) = 0, F(1) = 1
x, y = 0, 1
for _ in range(n):
x, y = y, x + y
return x, y
small, big = fib_pair(1500)
print(gcd(big, small)) # 1, after roughly 1500 steps
print(sys.getrecursionlimit()) # usually 1000
try:
gcd_recursive(big, small)
except RecursionError:
print("RecursionError: too many steps for the recursive form")Common Implementation Errors
Most broken GCD functions fail in one of a few predictable ways. Know them so you can spot them in code review.
Error 1: Sequential Assignment
Splitting the tuple assignment into two lines changes its meaning:
def gcd_broken(a, b):
while b != 0:
a = b
b = a % b # a already equals b here, so this is b % b == 0
return a
print(gcd_broken(1071, 462)) # 462, wrong (should be 21)After a = b, the old value of a is gone, so a % b becomes b % b, which is always 0. The loop runs once and returns the original b. If your language has no tuple assignment, use a temporary variable:
def gcd_temp(a, b):
a, b = abs(a), abs(b)
while b != 0:
r = a % b
a = b
b = r
return a
print(gcd_temp(1071, 462)) # 21Error 2: Returning the Wrong Variable
When the loop ends, b is 0 and a holds the GCD. Returning b gives 0 for every input. Some people make this mistake after misremembering the shortcut "the last non-zero remainder". That remainder sits in a once the loop has shifted it there.
Error 3: Using Division Instead of Remainder
Writing a // b where a % b belongs replaces the remainder with the quotient. The quotient has nothing to do with the GCD. For (1071, 462) this produces the pairs (462, 2), (2, 231), (231, 0), and the function returns 231.
Error 4: Floating-Point Arithmetic
Using /, or passing floats, brings in rounding. 1e20 % 3 is computed on an approximate value, and above 2^53 a float cannot represent every integer exactly. Keep everything in int.
Error 5: Testing the Wrong Number for Zero
A loop written as while a != 0 with the same body stops too early or too late, depending on which variable ends up holding the result. The value that becomes zero is the second element of the pair, so test that one.
Testing Against a Reference
Python's standard library already provides math.gcd. Use it as a reference to check your own versions on many random inputs, including zeros:
import math
import random
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
def gcd_recursive(a, b):
if b == 0:
return abs(a)
return gcd_recursive(b, a % b)
random.seed(0)
for _ in range(10_000):
a = random.randint(-10**6, 10**6)
b = random.randint(-10**6, 10**6)
expected = math.gcd(a, b)
assert gcd(a, b) == expected, (a, b)
assert gcd_recursive(a, b) == expected, (a, b)
# Hand-picked cases
assert gcd(0, 0) == 0
assert gcd(0, 5) == 5
assert gcd(7, 0) == 7
assert gcd(17, 5) == 1
print("all tests passed")Beyond comparing outputs, you can test the properties that define a GCD. The result g must divide both inputs, and gcd(a // g, b // g) must equal 1 whenever g > 0. Property checks like these catch bugs even when no reference implementation is available.
Exercises
Exercise
Trace Euclid's algorithm by hand on gcd(252, 105). Write each step as an equation a = q · b + r and give the result.
Show answer
252 = 2 · 105 + 42, then 105 = 2 · 42 + 21, then 42 = 2 · 21 + 0. The second number is now 0, so gcd(252, 105) = 21. Check: 252 = 21 · 12 and 105 = 21 · 5, and 12 and 5 share no common factor.
Exercise
How many division steps does the iterative gcd take on (89, 55), and what does it return? What is special about these inputs?
Show answer
The steps are 89 = 1·55 + 34, 55 = 1·34 + 21, 34 = 1·21 + 13, 21 = 1·13 + 8, 13 = 1·8 + 5, 8 = 1·5 + 3, 5 = 1·3 + 2, 3 = 1·2 + 1, 2 = 2·1 + 0. That is 9 steps, and the result is 1. The numbers 89 and 55 are consecutive Fibonacci numbers, so every quotient except the last is 1 and each remainder is the previous Fibonacci number. This is the slowest possible case for inputs of this size, which a later chapter proves.
Exercise
A colleague writes a loop body as "a = b" followed by "b = a % b". What does the function return for gcd(48, 18), and why?
Show answer
It returns 18. After "a = b", a equals 18, so "b = a % b" computes 18 % 18 = 0. The loop ends after one pass and returns a, which is the original b. Fix it with the tuple assignment "a, b = b, a % b" or with a temporary variable that holds the remainder.
Exercise
Why does gcd_recursive(big, small) raise RecursionError for consecutive Fibonacci numbers F(1501) and F(1500) in Python, while the iterative version succeeds?
Show answer
Each step of the recursive version adds a stack frame, and consecutive Fibonacci inputs need about one step per index, roughly 1500 steps here. That exceeds CPython's default recursion limit of 1000. Python does not turn tail calls into loops. The iterative version reuses the same two variables, so its memory use stays constant however many steps it takes.