Replace the problem with a smaller equivalent one.
Euclid’s algorithm preserves the common divisors of two integers while replacing the larger problem with a remainder pair that quickly becomes smaller.
Why does replacing a and b with b and the remainder preserve their greatest common divisor?
- Read remainder as the next problem state
- Identify the common-divisor invariant across calls
- Follow an exact integer process to its zero base case
- Compare the shrinking call sequence with the final answer
If a number divides both a and b, it also divides the remainder after a is divided by b. The reverse direction holds as well, so the pair changes while its greatest common divisor does not.
Each call replaces (a, b) with (b, remainder(a, b)). When the second value reaches zero, the first value is the preserved greatest common divisor. No postponed arithmetic remains after the recursive call.
(begin
(define (euclid a b)
(if (= b 0)
a
(euclid b (remainder a b))))
(euclid 206 40))- Output
- —
- Value
- —
- Diagnostic
- —
The first program returns 2. The second returns 21.
Follow (206, 40), (40, 6), (6, 4), (4, 2), and (2, 0). The second argument strictly shrinks until the base case exposes the invariant answer.
Change the program before you read the hint.
Run euclid with 1999 and 97. Write every argument pair before revealing the final greatest common divisor.
Show one hint
Apply remainder to the current pair and move the old second value into the first position.