Sub topic 11
Does It Stop? Arguing Termination
An algorithm must finish after a finite number of steps. That is the finiteness property from earlier in this tutorial. If a procedure might run forever on some valid input, it is not an algorithm for that problem, even if every answer it does produce is correct. This chapter shows how to argue that a loop stops instead of hoping it does.
This chapter assumes you can read simple Python, use while and for loops, and compute remainders with %. It also assumes you have seen the problem specification for Euclid's GCD algorithm (inputs a >= 0, b >= 0, not both zero) and can trace a loop with a state table.
Why Testing Is Not Enough
Running a program on ten inputs and seeing it stop each time tells you about those ten inputs only. A loop can finish on every input you try and still hang on one you did not try. Here is a small example:
def count_down_by_two(x):
steps = 0
while x != 0:
x -= 2
steps += 1
return steps
print(count_down_by_two(10)) # 5
print(count_down_by_two(4)) # 2
# count_down_by_two(7) never returns: x goes 7, 5, 3, 1, -1, -3, ...Every even test passes. The first odd input loops forever, because x jumps over 0. To be sure a loop stops, you need an argument that covers every input the precondition allows.
The Decreasing Measure
The standard argument uses a decreasing measure, also called a variant or ranking function. This is an expression built from the algorithm's variables that has three properties:
- It is a whole number. It takes values in the integers, not real numbers.
- It has a lower bound. It can never drop below some fixed value, usually 0, while the loop is still running.
- It strictly decreases. Every iteration makes it smaller by at least 1.
If all three hold, the loop must stop. A non-negative integer that drops by at least 1 each time can only drop a finite number of times. If the measure starts at value m, the loop runs at most m iterations.
Finding the measure is the creative step. Checking the three properties is routine once you have it.
Worked Example: Euclid's Algorithm
Recall the loop:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6Measure: b.
- Integer. The inputs are integers, and
a % bof two integers is an integer, sobstays an integer. - Bounded below. The precondition says
b >= 0. Whenb > 0, Python'sa % blies in the range0tob - 1, so the newbis also>= 0. - Strictly decreases. The loop body only runs when
b != 0, which combined withb >= 0meansb > 0. The new value ofbisa % b, which is at mostb - 1. Sobdrops by at least 1.
The loop therefore runs at most b times (the initial value of b). Tracing gcd(48, 18) gives b values 18, 12, 6, 0, which is a strictly decreasing sequence, as the argument predicts. (Euclid actually finishes much faster than b iterations, but the measure only needs to give some finite bound.)
Note how the argument used the precondition. The fact that b >= 0 is what makes the lower bound hold. Termination arguments almost always depend on the precondition, and that is one reason a precise specification matters.
Worked Example: Linear Search
def linear_search(items, target):
for i, x in enumerate(items):
if x == target:
return i
return -1A Python for loop over a list hides the counter, so make it explicit. The loop visits positions i = 0, 1, ..., n - 1, where n = len(items). The measure is n - i, the number of positions not yet examined. It is an integer, it never goes below 0, and it drops by 1 each iteration. The early return only makes the loop stop sooner, which never threatens termination.
The general lesson is that a for loop over a finite collection that is not modified during the loop always terminates. The measure is "items remaining". while loops are where you need to think.
Checking a Measure While You Develop
You can turn a termination argument into runtime checks. This does not prove anything, but it catches a wrong measure quickly during testing.
def gcd_checked(a, b):
assert a >= 0 and b >= 0 and not (a == 0 and b == 0), "precondition"
while b != 0:
measure_before = b
a, b = b, a % b
assert isinstance(b, int), "measure must be an integer"
assert b >= 0, "measure must stay bounded below"
assert b < measure_before, "measure must strictly decrease"
return a
print(gcd_checked(48, 18)) # 6
print(gcd_checked(17, 5)) # 1
print(gcd_checked(0, 9)) # 9Common Mistakes and Gotchas
The measure decreases on some paths only
The measure has to decrease on every path through the loop body. A branch that skips the update is a common source of hangs. Binary search shows the classic case:
def binary_search(xs, target):
# Precondition: xs is sorted in ascending order
lo, hi = 0, len(xs) # search the half-open range [lo, hi)
while lo < hi:
mid = (lo + hi) // 2
if xs[mid] < target:
lo = mid + 1 # writing lo = mid here can loop forever
else:
hi = mid
if lo < len(xs) and xs[lo] == target:
return lo
return -1
print(binary_search([1, 3, 5, 7, 9], 7)) # 3
print(binary_search([1, 3, 5, 7, 9], 4)) # -1The measure is hi - lo. Since lo <= mid < hi, both branches shrink it: lo = mid + 1 moves lo up by at least 1, and hi = mid moves hi down by at least 1. If you write lo = mid instead, then when hi - lo == 1 you get mid == lo and nothing changes. The measure stays the same and the loop never ends.
Decreasing is not enough without a bound
The value x in count_down_by_two does decrease on every step. It fails because it is not bounded below: it passes 0 and keeps going. Both properties are required.
Real numbers can decrease forever
A real-valued quantity can shrink forever without hitting a bound. The values 1, 0.5, 0.25, ... all decrease and all stay above 0. That is why the measure must be an integer, or more generally must come from a set with no infinite decreasing chains. Floating-point loops such as while x > 0: x = x / 2 do stop in practice only because floats have finite precision and x eventually underflows to 0. That is a fact about the hardware, not a reasoned argument, so avoid relying on it.
Nested loops and multi-part measures
For nested loops, argue each loop separately: the inner loop terminates for each fixed state of the outer loop, and the outer loop's measure decreases each outer iteration. Sometimes one number is not enough and you need a pair compared lexicographically. For example, (outer_remaining, inner_remaining) decreases if either the first part drops, or the first part stays the same and the second drops.
Some loops have no known argument
Nobody has a termination proof for this loop:
def collatz_steps(n):
# Precondition: n is a positive integer
steps = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
return steps
print(collatz_steps(27)) # 111It has stopped on every input anyone has tested, but whether it stops for all positive n is an open problem, the Collatz conjecture. More broadly, Turing's halting theorem shows that no general method can decide termination for every program. Termination is something you build into an algorithm through its design, and you justify it with a measure. You cannot hand an arbitrary program to a tool and get a guaranteed answer.
Termination and Correctness Are Separate Claims
Showing that an algorithm stops does not show that its answer is right, and showing that any answer it returns is right does not show it stops. People call the second claim partial correctness. Total correctness is partial correctness plus termination. The next chapter adds loop invariants, the tool for the partial-correctness half. The measure from this chapter supplies the other half. Recursive algorithms use the same idea, with the measure decreasing on each recursive call instead of each iteration, and that case is covered later in the tutorial.
| Claim | Question it answers | Typical tool |
|---|---|---|
| Partial correctness | If it stops, is the answer right? | Loop invariant |
| Termination | Does it stop on every valid input? | Decreasing measure |
| Total correctness | Does it stop with the right answer? | Both together |
Exercise
Give a decreasing measure for this loop and check all three properties. Precondition: n is a non-negative integer. total = 0 while n > 0: total += n % 10 n = n // 10
Show answer
Use n itself. It is an integer because integer division of an integer by 10 gives an integer. It is bounded below because n >= 0 by the precondition, and n // 10 >= 0 whenever n >= 0. It strictly decreases because the body runs only when n > 0, and for n > 0 we have n // 10 < n. So the loop terminates, in fact after as many iterations as n has decimal digits.
Exercise
A student writes while lo <= hi: with mid = (lo + hi) // 2, lo = mid + 1 in one branch and hi = mid in the other, starting from lo = 0, hi = len(xs) - 1. Find a case where it fails to terminate, and name which measure property breaks.
Show answer
Use xs = [5] and target 9. Then lo = hi = 0, mid = 0, and since xs[0] < 9, lo becomes 1, so the loop exits. Now try target 1: xs[0] < 1 is false, so hi = mid = 0. lo and hi are unchanged, so the loop repeats forever. The candidate measure hi - lo + 1 stays at 1, so strict decrease fails on the else branch. With an inclusive range the fix is hi = mid - 1.
Exercise
Does while x > 0: x = x - 0.5 terminate for every positive integer x? Is x a valid decreasing measure?
Show answer
It terminates: the values are x, x - 0.5, ..., and after 2x steps x reaches 0 exactly (0.5 is exactly representable in binary, so there is no rounding). But x is not a valid measure as stated, because it takes non-integer values. Use 2x instead. It is an integer, it is at least 0 while the loop runs, and it drops by exactly 1 each iteration.