Sub topic 2
Euclid's Original Method: Repeated Subtraction
This chapter assumes you know the identity gcd(a, b) = gcd(b, a mod b) from the previous chapter, and that you can read Python loops and recursion.
Repeated Subtraction
Euclid stated his method with subtraction. Any common divisor of a and b also divides a − b. So you can replace the larger number with the difference and the GCD stays the same. When the two numbers become equal, that value is the GCD.
def gcd_subtraction(a, b):
# Assumes a > 0 and b > 0
while a != b:
if a > b:
a -= b
else:
b -= a
return a
print(gcd_subtraction(48, 18)) # 6The steps for 48 and 18 are (48, 18) → (30, 18) → (12, 18) → (12, 6) → (6, 6). When one input is much larger than the other, this method takes many steps. Each run of repeated subtractions of b computes a mod b, so you can do that whole run with a single % operation.
Tracing and Implementing the Division Form
Here is the division form traced for 1071 and 462:
| a | b | a mod b |
|---|---|---|
| 1071 | 462 | 147 |
| 462 | 147 | 21 |
| 147 | 21 | 0 |
| 21 | 0 | stop |
The result is 21.
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)
print(gcd(1071, 462)) # 21
print(gcd_recursive(48, 18)) # 6Zero and Negative Inputs
- gcd(a, 0) = |a|, because every integer divides 0. By convention gcd(0, 0) = 0, and both functions above return 0 for it.
- Signs do not change the set of divisors, so take absolute values first. In Python,
%takes the sign of the divisor, which means7 % -3is-2. Callingabsfirst keeps every remainder non-negative.
Termination and Correctness
Termination. Each step replaces b with r = a mod b, and 0 ≤ r < b. The values of b form a strictly decreasing sequence of non-negative integers, so the sequence must reach 0 after a finite number of steps.
Correctness. The invariant gcd(a, b) = gcd(b, a mod b) holds at every step, so the GCD of the current pair always equals the GCD of the original inputs. The loop stops when the pair is (a, 0), and gcd(a, 0) = a.
Exercise
Trace the division form of Euclid's algorithm on (252, 105). List each pair and give the result.
Show answer
(252, 105) → (105, 42) → (42, 21) → (21, 0). The GCD is 21.
Exercise
Why does the termination argument for the division form not apply to gcd_subtraction(0, 5)?
Show answer
Subtracting 0 leaves b unchanged, so no value strictly decreases and the loop condition a != b stays true forever.