Sub topic 5
The Algorithm: Tracing and Implementing It
This chapter assumes you know integer division and the % (modulo) operator, can read short Python functions with loops and recursion, and accept the invariant from the earlier chapter: gcd(a, b) = gcd(b, a mod b). Here you will use that invariant to trace the algorithm by hand, then turn it into code.
The working model
Euclid's algorithm keeps a pair of numbers. At each step it replaces the pair (a, b) with (b, a mod b). The invariant says the GCD of the pair never changes. The second number keeps shrinking, so it eventually reaches 0. At that point the pair is (g, 0), and gcd(g, 0) = g. The first number is the answer.
Tracing by hand: gcd(1071, 462)
Write each step as a division with remainder, a = q · b + r. Then shift the numbers one place to the left for the next row.
| Step | a | b | Division | a mod b |
|---|---|---|---|---|
| 1 | 1071 | 462 | 1071 = 2 · 462 + 147 | 147 |
| 2 | 462 | 147 | 462 = 3 · 147 + 21 | 21 |
| 3 | 147 | 21 | 147 = 7 · 21 + 0 | 0 |
| 4 | 21 | 0 | stop | — |
The last nonzero remainder is 21, so gcd(1071, 462) = 21. You can check it: 1071 = 21 · 51 and 462 = 21 · 22, and 51 and 22 share no factor.
The iterative implementation
The loop below does what the table does: it keeps shifting the pair until b is zero.
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
print(gcd(1071, 462)) # 21The abs calls make negative inputs give a non-negative result. The next chapter covers zero and negative inputs in detail.
The recursive implementation
The recursive form is the invariant written as code. The base case is gcd(a, 0) = |a|, and the recursive case is gcd(a, b) = gcd(b, a mod b).
def gcd_recursive(a, b):
if b == 0:
return abs(a)
return gcd_recursive(b, a % b)
print(gcd_recursive(48, 18)) # 6Here is the call chain for 48 and 18: gcd_recursive(48, 18) calls gcd_recursive(18, 12), which calls gcd_recursive(12, 6), which calls gcd_recursive(6, 0), which returns 6.
Python limits recursion depth to about 1000 frames by default. That limit is not a problem here, because the number of steps grows with the number of digits in the inputs, not with their size. A later chapter proves this bound. Even so, the iterative version avoids the stack entirely, and most library code uses that form.
Common errors
Most bugs in hand-written versions come from a few mistakes.
- Updating the variables one at a time. Writing
a = band thenb = a % bcomputesb % b, which is always 0. Python's tuple assignmenta, b = b, a % bevaluates the right side before it assigns anything. In languages without tuple assignment, store the remainder in a temporary variable first. - Returning the wrong variable. When the loop ends,
bis 0 and the answer is ina. - Testing the wrong condition. Looping
while a != 0instead ofwhile b != 0divides by zero on the step after the last nonzero remainder. - Mixing up the argument order in the recursive call.
gcd_recursive(a % b, b)never shrinks the pair in the right way. The call must begcd_recursive(b, a % b).
Exercise
Trace Euclid's algorithm by hand on gcd(252, 105). List each division and give the result.
Show answer
252 = 2 · 105 + 42, then 105 = 2 · 42 + 21, then 42 = 2 · 21 + 0. The last nonzero remainder is 21, so gcd(252, 105) = 21.
Exercise
A colleague writes the loop body as a = b followed by b = a % b. What does gcd(48, 18) return, and why?
Show answer
It returns 18. After a = b, a is 18, so b = 18 % 18 = 0 and the loop exits with a = 18. The remainder must be computed from the old values, for example with a, b = b, a % b.
Exercise
How many division steps does gcd(18, 48) take, and what happens in the first step?
Show answer
Four. The first step computes 18 mod 48 = 18, which turns the pair into (48, 18). The next three steps give (18, 12), (12, 6), and (6, 0), and the result is 6.