Sub topic 7
Proving Termination and Correctness
This chapter assumes you know the invariant gcd(a, b) = gcd(b, a mod b) from the earlier chapter, the iterative and recursive implementations, and the basics of proof by induction. Here we prove two separate claims about Euclid's algorithm. The first is that it always stops. The second is that the value it returns when it stops really is the greatest common divisor. These are different properties, and a buggy variant can have one without the other.
Two Separate Obligations
Computer scientists split the correctness of a loop into two parts:
- Partial correctness means that if the loop stops, its answer is right.
- Termination means that the loop does stop, on every allowed input.
Together these give total correctness. Keep them apart. A loop that never stops is partially correct by default, because it never returns a wrong answer. A loop that always stops but returns the wrong number terminates and is still wrong.
Here is the version we will prove correct:
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
print(gcd(1071, 462)) # 21Each obligation has its own tool. Partial correctness uses a loop invariant, which is a statement that is true before the loop starts and stays true after every iteration. Termination uses a variant (also called a measure or ranking function), which is a non-negative integer that strictly decreases on every iteration.
Partial Correctness via the Loop Invariant
Let a₀ and b₀ be the original inputs, and let G = gcd(a₀, b₀). The invariant is:
> gcd(a, b) = G, and a ≥ 0, b ≥ 0.
We check three things.
Initialization
Before the loop runs, the code replaces a and b with their absolute values. An integer d divides x exactly when it divides −x, because x = dk implies −x = d(−k). So a and |a| have the same set of divisors. That means gcd(|a₀|, |b₀|) = gcd(a₀, b₀) = G. Both values are now non-negative, so the invariant holds on entry.
Maintenance
Suppose the invariant holds at the start of an iteration and b ≠ 0. The body sets the new pair to (b, a mod b). By the identity proved earlier, gcd(b, a mod b) = gcd(a, b) = G. The new first value is the old b, which is ≥ 0. The new second value is a mod b. In Python, a mod b is in the range 0 ≤ a mod b < b whenever b > 0. So both values stay non-negative, and the invariant holds again.
Exit
The loop exits only when b = 0. At that point the invariant tells us gcd(a, 0) = G. Every integer divides 0, so the common divisors of a and 0 are just the divisors of a. For a > 0 the largest of these is a itself. For a = 0 we use the usual convention gcd(0, 0) = 0. Either way gcd(a, 0) = a when a ≥ 0, so the returned value a equals G.
Note that the non-negativity part of the invariant is doing real work here. If a could be negative at exit, the function would return −G.
Termination via a Decreasing Variant
The variant is the current value of b.
- It is a non-negative integer. This is part of the invariant.
- It strictly decreases. When the loop body runs, b > 0, and the new value of b is a mod b, which satisfies a mod b < b.
A strictly decreasing sequence of non-negative integers cannot go on forever. This is the well-ordering principle: every non-empty set of natural numbers has a least element, so there is no infinite chain b₁ > b₂ > b₃ > ⋯ ≥ 0. The loop therefore runs at most b₀ times, where b₀ = |b₀| after the absolute value step.
That bound is true but very weak. The input (1000001, 1000000) would allow a million iterations, yet the loop actually finishes in two. A sharper argument follows.
The Remainder Halves Every Two Steps
Write the sequence of values that pass through the second slot as r₁ = b, r₂, r₃, …, where each rₖ₊₂ = rₖ mod rₖ₊₁.
Lemma. If rₖ₊₁ > 0, then rₖ₊₂ < rₖ / 2.
Proof. There are two cases.
- If rₖ₊₁ ≤ rₖ / 2, then rₖ₊₂ < rₖ₊₁ ≤ rₖ / 2, because a remainder is always smaller than its divisor.
- If rₖ₊₁ > rₖ / 2, then rₖ₊₁ goes into rₖ exactly once (since 2·rₖ₊₁ > rₖ and rₖ₊₁ < rₖ). So rₖ₊₂ = rₖ − rₖ₊₁ < rₖ − rₖ / 2 = rₖ / 2.
In both cases the remainder two steps later is less than half. ∎
Each pair of iterations at least halves the variant, so the number of iterations is less than 2·log₂(b) + 2 for b > 0. The loop count grows with the number of digits of the input, not with its size. The chapter on Lamé's theorem tightens this bound by finding the exact worst-case inputs.
Checking the Proof in Code
A proof is the real guarantee, but turning the invariant and variant into assertions is a cheap way to catch mistakes in either the proof or the code. The checker below uses a brute-force GCD as an independent reference, so it does not assume the thing it is testing.
import math
def gcd_brute(a, b):
# Reference GCD by trying every candidate divisor; a, b >= 0
if a == 0 and b == 0:
return 0
return max(d for d in range(1, max(a, b) + 1)
if a % d == 0 and b % d == 0)
def gcd_checked(a, b):
a, b = abs(a), abs(b)
target = gcd_brute(a, b)
b_start = b
steps = 0
while b != 0:
# Invariant: same gcd, both values non-negative
assert gcd_brute(a, b) == target and a >= 0 and b >= 0
old_b = b
a, b = b, a % b
# Variant: strictly decreasing, never negative
assert 0 <= b < old_b
steps += 1
# Postcondition
assert a == target
if b_start > 0:
assert steps < 2 * math.log2(b_start) + 2
return a
count = 0
for x in range(-40, 41):
for y in range(-40, 41):
gcd_checked(x, y)
count += 1
print(f"checked {count} pairs") # checked 6561 pairsEvery pair in the range passes all four assertions, including pairs where one or both inputs are zero or negative.
Proving the Recursive Version by Strong Induction
The recursive form has no loop, so we use induction instead of an invariant:
def gcd_recursive(a, b):
if b == 0:
return abs(a)
return gcd_recursive(b, a % b)
print(gcd_recursive(48, 18)) # 6Claim. For every integer a and every integer b ≥ 0, gcd_recursive(a, b) terminates and returns gcd(a, b).
Proof by strong induction on b.
- Base case, b = 0. The function returns |a|, and gcd(a, 0) = |a|.
- Inductive step, b > 0. Assume the claim holds for every second argument smaller than b. The function calls itself with second argument a mod b, and 0 ≤ a mod b < b. By the inductive hypothesis, that call terminates and returns gcd(b, a mod b). By the invariant identity, this equals gcd(a, b). ∎
Strong induction proves termination and correctness in a single argument. The recursion depth is the same as the iteration count of the loop, so the halving lemma also bounds the stack depth. Even for 1000-digit inputs the depth is only a few thousand frames at most. In practice it is far smaller, and well below Python's default limit of 1000 for inputs of a few hundred digits.
What About Negative b?
The claim above requires b ≥ 0. With negative b, Python's a % b has the sign of b and satisfies b < a % b ≤ 0. The proof still works if you use |b| as the variant, because |a % b| < |b|. Likewise, in C, Java, and Go, % truncates toward zero and the result takes the sign of a, yet |a % b| < |b| still holds. Use |b| as the variant and the proof carries over to any language. The abs call at the end of the base case then fixes the sign of the result.
How Broken Variants Fail
Each piece of the proof matches a specific way to break the code. Looking at which piece fails tells you which kind of bug you have.
| Variant of the code | Piece of the proof that fails | Symptom |
|---|---|---|
| `while b > 0` with no `abs` | Exit: loop can stop with b < 0 | `gcd(12, -8)` returns 12 |
| No `abs`, `return a` at end | Invariant: a ≥ 0 not maintained | `gcd(-12, 0)` returns −12 |
| Subtraction form with a zero input | Variant: subtracting 0 does not decrease anything | `gcd_subtraction(0, 5)` loops forever |
| Float inputs such as `gcd(0.3, 0.1)` | Well-ordering: reals have infinite descending chains | Rounding error gives a tiny remainder such as 0.0999… instead of 0, so the answer is garbage |
The subtraction case deserves a closer look. The earlier subtraction method assumes a > 0 and b > 0. Its variant is a + b, which drops by min(a, b) on each step. When one input is 0, the drop is 0, the variant stops decreasing, and the termination proof is gone. The precondition is a required part of the proof, and calling the function outside it is a real bug.
Summary of the Argument
| Obligation | Tool | Key fact used |
|---|---|---|
| Invariant holds initially | abs preserves divisors | d divides x if and only if d divides −x |
| Invariant is maintained | Invariant lemma | gcd(a, b) = gcd(b, a mod b) |
| Answer is right at exit | b = 0 and a ≥ 0 | gcd(a, 0) = a |
| Loop stops | Variant b | 0 ≤ a mod b < b and well-ordering |
| Loop stops quickly | Halving lemma | rₖ₊₂ < rₖ / 2 |
Exercise
The buggy function below drops the abs call and uses while b > 0. Which part of the correctness proof fails, and what does gcd_bad(12, -8) return?
def gcd_bad(a, b):
while b > 0:
a, b = b, a % b
return a
Show answer
The exit step fails. The proof needs b = 0 at exit so that gcd(a, 0) = a. Here the loop also exits when b is negative, and gcd(a, b) does not equal a in general. With b = −8 the loop body never runs, so the function returns 12, but gcd(12, −8) = 4.
Exercise
Prove that gcdsubtraction(a, b) terminates for all a > 0 and b > 0 by naming a variant and showing it strictly decreases. Then explain exactly where the argument breaks for gcdsubtraction(0, 5).
Show answer
Use the variant a + b. Both values stay positive, because we always subtract the smaller from the strictly larger, so a + b is a positive integer. Each step subtracts min(a, b) ≥ 1 from it, so it strictly decreases, and by well-ordering the loop stops. For (0, 5), the else branch sets b = 5 − 0 = 5, so min(a, b) = 0, the variant does not change, and the loop never ends.
Exercise
Trace the remainder sequence for gcd(1071, 462) and check the halving lemma on every triple rₖ, rₖ₊₁, rₖ₊₂ where rₖ₊₁ > 0.
Show answer
The sequence is 1071, 462, 147, 21, 0. For (1071, 462, 147): 147 < 535.5. For (462, 147, 21): 21 < 231. For (147, 21, 0): 0 < 73.5. The lemma holds at every step. The loop takes 3 iterations, which is below the bound 2·log₂(462) + 2 ≈ 19.7.
Exercise
Why does the strong induction proof for gcd_recursive need strong induction instead of ordinary induction on b?
Show answer
The recursive call uses a mod b as its second argument, and this can be any value from 0 to b − 1, not necessarily b − 1. Ordinary induction only lets you assume the claim for b − 1. Strong induction lets you assume it for every value below b, which covers whatever a mod b turns out to be.