Module contents
Lesson 8 of 22Core 110 min

Algorithm correctness: loop invariants and termination

Proving an algorithm correct: distinguish partial and total correctness, build inductive loop invariants and variants over well-founded orders, and apply them to binary search, partitioning, insertion sort, extended Euclid, fast exponentiation and modular arithmetic.

After this lesson you can

  • Specify a loop and distinguish partial from total correctness
  • Find inductive invariants and verify initialization, maintenance and sufficiency on exit
  • Prove termination using a variant function on a well-founded order
  • Prove recursive algorithms correct by induction on the call measure
  • Prove extended Euclid and fast exponentiation using invariants
  • Instrument code with executable invariants and detect true but noninductive invariants

Before you start

Motivation: a correct proof of an incorrect program

In Programming Pearls, Jon Bentley recounts asking professional programmers to write binary search and around 90% finding errors in their own code. He wrote a version himself, proved it correct using an invariant, and tested it. In 2006 Joshua Bloch reported a bug in that version, which binary search in java.util.Arrays, written by him using the same pattern, had carried for about nine years. The bug was in an apparently foolproof line:

int mid = (low + high) / 2;

With 32-bit integers, if the array has more than 2302^{30} elements, low + high can exceed 231−12^{31} - 1 and wrap to a negative number. The resulting index is negative and the program crashes. Bentley’s proof was not wrong: it reasoned about mathematical integers. The program ran on 32-bit integers.

[ ]The overflowing midpointBrowser
import numpy as np

lo = np.array([1_500_000_000], dtype=np.int32)     # dos índices válidos de un array
hi = np.array([2_000_000_000], dtype=np.int32)     # de más de 2^30 elementos
print("lo + hi en int32       :", (lo + hi)[0])
print("(lo + hi) // 2         :", ((lo + hi) // 2)[0])
print("lo + (hi - lo) // 2    :", (lo + (hi - lo) // 2)[0])
print("(lo + hi) >>> 1 (Java) :", ((lo + hi).view(np.uint32) >> 1)[0])
print("en Python, sin límite  :", (1_500_000_000 + 2_000_000_000) // 2)

The story supplies two lessons organizing this one. First, a correctness proof is relative to a model: a specification and operation semantics. If the model says “integers” and the machine says “integers modulo 2322^{32},” the proof does not cover the failing case. Second, invariant reasoning worked. It localized everything model-dependent to one obligation (that mid lie between lo and hi), and rewriting the midpoint as lo + (hi - lo) // 2, which never exceeds hi, made the same proof apply to 32 bits.

This lesson makes that reasoning a method. A loop is proved with two objects: an invariant stating what is true on each pass, checked by three independent obligations; and a variant, a quantity decreasing on each pass in an order without infinite descending chains. You already have the tools: induction from lesson 5, well-founded orders from lesson 6, and specifications from lesson 2. We apply them to algorithms frequently implemented incorrectly (binary search, partitioning, sorting) and arithmetic behind cryptography and hashing (Euclid, Bézout, modular inverses and fast exponentiation).

Intuition: the invariant is a picture

In a sorted array a of length nn, find the lower bound of xx: the first index kk with ak≥xa_k \ge x, or nn if none exists. This is the basic binary-search operation (bisect_left in Python, lower_bound in C++), answering “is xx present?”, “where should it be inserted?” and “how many elements are below xx?”

lo, hi = 0, len(a)
while lo < hi:
    mid = lo + (hi - lo) // 2
    if a[mid] < x: lo = mid + 1
    else:          hi = mid
return lo

Why does it work? Draw the array divided into three regions by lo and hi. Left of lo everything is less than xx. From hi to the end everything is at least xx. Between them is an unexamined region. Initially the unknown region is the whole array and the picture is immediately true. Each pass examines the middle of the unknown region and, since the array is sorted, can assign half to one side without making the picture false. When the unknown region empties, lo and hi coincide and the picture says exactly that lo is the answer.

That picture is the invariant. It describes what remains true as the loop runs.

InteractiveThe invariant painted on the array
?10212233545556778889910911lohi
step 0 of 4
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] < x: lo = mid + 1
else: hi = mid
return lo
Invariant, clause by clause
0≤lo≤hi≤n0 \le \mathit{lo} \le \mathit{hi} \le n
aj<x para todo j<loa_j < x \text{ para todo } j < \mathit{lo}
aj≥x para todo j≥hia_j \ge x \text{ para todo } j \ge \mathit{hi}
Start: lo = 0, hi = n = 12. The entire array is unknown and the invariant holds trivially.
  • less than xx
  • greater than or equal to xx
  • contradicts its region
Algorithm
5
Invariant at this stepholds
hi−lo\mathit{hi} - \mathit{lo}12
Correct lower bound4
Step through. Cells are colored by the region assigned by the invariant, and each clause is evaluated in the current state; a red-bordered cell contradicts its region. Then choose a buggy version: with ‘hi = mid − 1’ find the exact step breaking the third clause; with ‘lo = mid’ observe the invariant survives but the variant stops; with guard ‘lo ≤ hi’ also try x=10x = 10. In Dutch national flag, the extra ‘i += 1’ breaks the equal region as soon as an unexamined element enters it.

The figure’s three bugs fail in different ways, corresponding to different proof obligations:

  1. With hi = mid - 1, for x=5x = 5 step three sets hi = 3 when a3=3<5a_3 = 3 < 5: the picture claims cell 3 is right of the boundary but it is not. Invariant maintenance breaks. The loop terminates and returns 3 instead of 4.
  2. With lo = mid the invariant never breaks (saying everything before mid is less than xx is weaker than saying so through mid, and remains true). But when the unknown region has one cell and it is less than xx, lo does not move. Only termination fails: the program is partially correct but never returns.
  3. With guard lo <= hi, the loop enters with an empty unknown region. If lo = hi < n, mid = lo and hi = mid changes nothing: no termination again. If lo = hi = n, it reads a[n] outside the array. The guard must ensure the unknown region is nonempty, the only way mid is a valid index and variant hi - lo decreases.

Specification, partial correctness and total correctness

A program is correct relative to a specification. As in formal specification, a specification is a pair of state predicates: a precondition PP the caller promises to satisfy, and a postcondition QQ the program promises to establish. For lower bound, PP says a is nondecreasing and QQ says result kk satisfies 0≤k≤n0 \le k \le n, aj<xa_j < x for every j<kj < k, and aj≥xa_j \ge x for every j≥kj \ge k.

Write {P} S {Q}\{P\}\ S\ \{Q\} to say fragment SS satisfies specification (P,Q)(P, Q). There are two possible readings; separating them is the first methodological decision.

Partial correctness alone is a weak guarantee. while True: pass is partially correct for any specification because it never terminates. A less silly example:

while x != 0:
    x = x - 2

It is partially correct for postcondition x=0x = 0 under any precondition: if it terminates, the guard is false, hence x=0x = 0. But it is totally correct only if the precondition ensures xx is even and nonnegative; with x=1x = 1 it traverses −1,−3,−5,…-1, -3, -5, \dots forever. Proving the properties separately helps: the invariant handles partial correctness, the variant termination, and each argument is shorter than the whole.

The loop as a state machine

To reason about while B: S, view it as a discrete dynamical system. A state σ\sigma assigns every variable a value; Σ\Sigma denotes the state set. The guard is a predicate BB on Σ\Sigma and the body, if deterministic, is a function T:Σ→ΣT: \Sigma \to \Sigma. An execution from σ0\sigma_0 is the sequence

σ0,σ1=T(σ0),σ2=T(σ1),…\sigma_0,\quad \sigma_1 = T(\sigma_0),\quad \sigma_2 = T(\sigma_1),\quad \dots

which stops at the first σk\sigma_k with ¬B(σk)\neg B(\sigma_k). The loop terminates from σ0\sigma_0 if that kk exists. The reachable states RR are all σk\sigma_k from executions beginning in states satisfying PP. If the body is nondeterministic (chooses among actions), TT is a relation and everything below holds by requiring conditions for every possible successor.

Loop invariants

Proof

Fix an execution σ0,σ1,…\sigma_0, \sigma_1, \dots beginning after Init from a state satisfying PP. Prove I(σk)I(\sigma_k) by induction on kk for every kk through the end of execution. For k=0k = 0 this is initialization. If I(σk)I(\sigma_k) and execution continues, B(σk)B(\sigma_k) holds, and maintenance gives I(T(σk))=I(σk+1)I(T(\sigma_k)) = I(\sigma_{k+1}). If execution ends at σk\sigma_k, then ¬B(σk)\neg B(\sigma_k), and with I(σk)I(\sigma_k) exit gives Q(σk)Q(\sigma_k).

∎

The proof is textbook induction; what matters is what makes it possible. Maintenance is required for every state satisfying I∧BI \wedge B, not just reachable states. This has a cost and a benefit. Cost: check states the program never visits. Benefit: checking is local, one isolated body iteration without simulating executions, so it can be done by hand, an automated prover or a random-state generator.

Inductive versus merely true

Call any predicate true in every reachable state an invariant property (R⊆IR \subseteq I), and one also satisfying maintenance an inductive invariant. Every inductive invariant with initialization is an invariant property by the loop rule. The converse is false, causing the most frequent loop-proof error. Consider:

# Pre: n >= 0
i, j = 1, 0
while i <= n:
    j = j + i
    i = i + 1
# Post: j >= 0

j≥0j \ge 0 is true in every execution and implies the postcondition. But it is not inductive: state i=−1i = -1, j=0j = 0, n=0n = 0 satisfies j≥0j \ge 0 and the guard, and after one pass gives j=−1j = -1. That state is unreachable because ii starts at 1 and only increases. But hypothesis “j≥0j \ge 0” does not know this, and maintenance can use only the hypothesis. This is the same as strengthening the induction hypothesis in lesson 5: the statement is true but cannot be proved as given; prove something stronger. Here j≥0∧i≥1j \ge 0 \wedge i \ge 1 suffices and is maintained: if j≥0j \ge 0 and i≥1i \ge 1, then j+i≥0j + i \ge 0 and i+1≥1i + 1 \ge 1.

There is always an inductive invariant implying any invariant property: the reachable set RR itself, closed under TT inside BB by definition. The problem is that RR rarely has a manageable description. Proving a loop means finding a predicate between RR and the desired property that is both inductive and expressible.

InteractivePropose an invariant and see which obligation fails
# Pre: n >= 0
i, j = 1, 0
while i <= n: # I is evaluated here
j = j + i
i = i + 1
# Post: j >= 0
Try:
0. True in executions✓ holds
what testing observes: II at the loop head, iteration by iteration
holds in all 28 states reached by executions from the box
1. Initialization✓ holds
Pre⇒I\text{Pre} \Rightarrow I after the initial assignment
checked in 7 states
2. Maintenance✗ fails
I∧B⇒II \wedge B \Rightarrow I after one iteration, for every state in the box satisfying Pre
fails in 147 of 1750 states; the smallest:
before: n = 0, i = −1, j = 0
after: n = 0, i = 0, j = −1
3. Exit✓ holds
I∧¬B⇒PostI \wedge \neg B \Rightarrow \text{Post}, for every state in the box satisfying Pre
checked in 875 states
Box: n∈[0,6]n \in [0, 6], i∈[−6,8]i \in [-6, 8], j∈[−4,24]j \in [-4, 24].
States in the box3045
States reached in executions28
True in every execution, but not inductive: some states satisfy it and the guard but leave it after one iteration. Those states are unreachable, but the proof cannot know that unless the invariant says so. Strengthen it.
Enter a candidate invariant for the selected loop. The tool checks initialization, maintenance and exit over all states in a bounded box, reachable or not, showing the smallest counterexample for each failed obligation. Card 0 does what a test does: check the predicate on executions. Start with ‘j >= 0’: card 0 passes and maintenance fails. Then try all four loops with their suggestions and find one candidate too strong, one too weak and one correct.

The four loops cover four diagnoses:

  • Too strong. In integer division, a=qb+r∧0≤r<ba = qb + r \wedge 0 \le r < b is exactly the postcondition and fails initialization: on entry r=ar = a can be at least bb (the box gives smallest case a=b=1a = b = 1).
  • Too weak. a=qb+ra = qb + r initializes and is maintained (subtracting bb from rr and adding 1 to qq does not change qb+rqb + r), but exit yields only r<br < b, and state q=1q = 1, r=−1r = -1, a=0a = 0, b=1b = 1 satisfies the invariant and false guard without satisfying the postcondition. r≥0r \ge 0 is missing.
  • True but not inductive. j≥0j \ge 0 in the preceding loop.
  • Correct. a=qb+r∧r≥0a = qb + r \wedge r \ge 0 for division; gcd⁡(x,y)=gcd⁡(a,b)∧x>0∧y>0\gcd(x, y) = \gcd(a, b) \wedge x > 0 \wedge y > 0 for subtraction Euclid.

A box counterexample is a genuine refutation: a legitimate state where an obligation fails. None appearing is only evidence, since the box is finite. The proof comes from the three-line algebra you can now write with confidence.

Finding invariants

There is no general algorithm (one would decide program termination, as Rice’s theorem shows in lesson 21), but three heuristics solve most practical loops, systematized by David Gries in The Science of Programming. All start from the postcondition, because the exit obligation says I∧¬BI \wedge \neg B must imply QQ.

Weaken the postcondition by removing a conjunct. If Q=Q1∧Q2Q = Q_1 \wedge Q_2 and Q2Q_2 easily becomes a negated guard, take I=Q1I = Q_1 and B=¬Q2B = \neg Q_2. In integer division, QQ is a=qb+r∧0≤r∧r<ba = qb + r \wedge 0 \le r \wedge r < b. Remove r<br < b: the invariant is a=qb+r∧0≤ra = qb + r \wedge 0 \le r and guard r≥br \ge b. On exit the false guard restores the missing conjunct.

Replace a constant with a variable. If QQ mentions constant nn, introduce ii moving from an endpoint to nn and write QQ with ii instead of nn. For a sum, QQ is s=∑k=1nks = \sum_{k=1}^{n} k and the invariant s=∑k=1ik∧0≤i≤ns = \sum_{k=1}^{i} k \wedge 0 \le i \le n, with guard i<ni < n. Bound i≤ni \le n is not decorative: without it, exit gives only i≥ni \ge n and the figure’s box finds state i=1i = 1, n=0n = 0, s=1s = 1. Forgetting index ranges is the most common oversight.

Divide the array into regions. When QQ quantifies over an array (“everything left of kk is less than xx”), draw the intermediate state as regions with known properties plus an unexplored region, and index each boundary. Lower bound replaces the postcondition’s single boundary kk with lo and hi, unknown region between. Dutch national flag has four regions and three boundaries. Insertion sort has two: sorted and remaining.

Once a candidate is written, the order of work is usually the same: check exit (which fixes its form), then maintenance branch by branch, and finally initialization, usually trivial because known regions start empty.

Termination: variant functions

An invariant says nothing about whether the loop ends. We need a measure of “work remaining” that cannot decrease forever.

Proof

Suppose an infinite execution σ0,σ1,…\sigma_0, \sigma_1, \dots from a state satisfying PP. The loop rule gives I(σk)I(\sigma_k) for all kk, and since execution does not stop, B(σk)B(\sigma_k) for all kk. Then V(σ0)≻V(σ1)≻V(σ2)≻⋯V(\sigma_0) \succ V(\sigma_1) \succ V(\sigma_2) \succ \cdots is an infinite descending chain in WW, contradicting well-foundedness of ≺\prec.

∎

For lower bound, V=hi−loV = \mathit{hi} - \mathit{lo}: under the invariant it is ≥0\ge 0, and under guard lo<hi\mathit{lo} < \mathit{hi} we have lo≤mid<hi\mathit{lo} \le \mathit{mid} < \mathit{hi}, so both lo←mid+1\mathit{lo} \leftarrow \mathit{mid} + 1 and hi←mid\mathit{hi} \leftarrow \mathit{mid} reduce it. The variant needs the invariant (to know it is ≥0\ge 0) and guard (to know it decreases). With lo = mid, the calculation fails exactly when mid=lo\mathit{mid} = \mathit{lo}, that is, hi−lo=1\mathit{hi} - \mathit{lo} = 1.

Two cautions about WW. First, it must be well-founded: decreasing VV alone is insufficient. Over reals, while x > 0: x = x / 2 decreases xx every pass and never terminates. In floating point it does terminate after 1075 passes if xx starts at 1, because 2−10752^{-1075} rounds to 0; a reason the mathematical model does not cover, just as the midpoint overflowed for an unmodeled reason. Second, N\N does not always suffice.

Lexicographic orders

Consider a loop on two naturals that each pass either decrements xx and assigns yy an arbitrary natural (chosen by a user, network or random generator), or decrements yy. Neither xx nor x+yx + y is a variant: the former does not decrease when yy does, the latter increases when yy jumps. What always decreases is the pair (x,y)(x, y) in lexicographic order:

(x′,y′)<lex(x,y)  ⟺  x′<x  or  (x′=x and y′<y).(x', y') <_{\text{lex}} (x, y) \iff x' < x \ \text{ or }\ (x' = x \text{ and } y' < y).

Lexicographic order on N×N\N \times \N is well-founded. In a descending chain first coordinates form a nonincreasing sequence of naturals, eventually stabilizing; thereafter second coordinates strictly decrease in N\N forever, impossible. The argument extends to Nd\N^d for any dd, and proves termination of Ackermann’s function or a parser alternating between consuming input and reducing a stack.

This loop admits no N\N-valued variant. If V:N2→NV: \N^2 \to \N decreased each step, chain (0,y)→(0,y−1)→⋯→(0,0)(0, y) \to (0, y - 1) \to \cdots \to (0, 0) would require V(0,y)≥yV(0, y) \ge y, and step (1,0)→(0,y)(1, 0) \to (0, y) would require V(1,0)>V(0,y)≥yV(1, 0) > V(0, y) \ge y for every yy. No natural exceeds all naturals. Lexicographic order is not just convenient: it is strictly more powerful.

InteractiveVariant functions versus Collatz
1101000510iteration kremainder b0
  • decreasing step
  • increasing step
  • b/2⌊k/2⌋b/2^{\lfloor k/2 \rfloor}
Loop
987
610
Iterations14
Steps increasing0
The remainder decreases at each step and is never negative: 14 divisions. The dashed bound is b/2⌊k/2⌋b/2^{\lfloor k/2 \rfloor}: the remainder is at least halved every two steps.
Variant value at each iteration; increasing stretches are red. In Euclid, the remainder decreases every step and the dashed bound shows it at least halves every two steps; try Fibonacci pair (987, 610). In binary search, hi−lo\mathit{hi} - \mathit{lo} halves each step. In the lexicographic loop see the path of (x,y)(x, y): jumps in yy increase x+yx + y, but the pair always decreases. In Collatz, nn rises and falls; find an nn with a long trajectory.

The final tab is the contrast. The Collatz loop, while n != 1: n = n // 2 if n % 2 == 0 else 3 * n + 1, terminates for every tested nn: 27 takes 111 steps and rises to 9232 before falling, and computer verification covers at least all n<268n < 2^{68} (Barina, 2021). But no variant function is known, and termination for all n≥1n \ge 1 is exactly the Collatz conjecture, open since 1937. Terence Tao proved in 2019 that “almost all” trajectories reach almost bounded values in a precise logarithmic-density sense, the furthest progress described here. A one-line loop resisting proof reminds us termination is generally undecidable.

Three case studies

Lower bound, proved completely

Proof

Initialization. With lo=0\mathit{lo} = 0 and hi=n\mathit{hi} = n, the range holds and both quantifiers range over empty sets.

Maintenance. Assume II and lo<hi\mathit{lo} < \mathit{hi}. Then mid=lo+⌊(hi−lo)/2⌋\mathit{mid} = \mathit{lo} + \lfloor(\mathit{hi} - \mathit{lo})/2\rfloor satisfies lo≤mid<hi≤n\mathit{lo} \le \mathit{mid} < \mathit{hi} \le n, so amida_{\mathit{mid}} exists. If amid<xa_{\mathit{mid}} < x, every j≤midj \le \mathit{mid} has aj≤amid<xa_j \le a_{\mathit{mid}} < x by sorting, so new lo=mid+1≤hi\mathit{lo} = \mathit{mid} + 1 \le \mathit{hi} satisfies the second clause; the others stay unchanged. If amid≥xa_{\mathit{mid}} \ge x, every j≥midj \ge \mathit{mid} has aj≥amid≥xa_j \ge a_{\mathit{mid}} \ge x, and new hi=mid≥lo\mathit{hi} = \mathit{mid} \ge \mathit{lo} satisfies the third.

Exit. II and ¬(lo<hi)\neg(\mathit{lo} < \mathit{hi}) give lo=hi\mathit{lo} = \mathit{hi}, and the quantified clauses with k=lok = \mathit{lo} give the postcondition. kk is unique: if k<k′k < k' both satisfied it, aka_k would be both <x< x and ≥x\ge x.

Termination. Under I∧BI \wedge B, V=hi−lo≥1V = \mathit{hi} - \mathit{lo} \ge 1 and both branches reduce it: hi−(mid+1)<hi−lo\mathit{hi} - (\mathit{mid} + 1) < \mathit{hi} - \mathit{lo} and mid−lo<hi−lo\mathit{mid} - \mathit{lo} < \mathit{hi} - \mathit{lo}.

∎

The proof gives more than correctness. Each pass leaves at most ⌊V/2⌋\lfloor V/2 \rfloor unknown elements, so there are at most ⌈log⁡2(n+1)⌉\lceil \log_2(n + 1) \rceil passes. And “amida_{\mathit{mid}} exists” is a safety obligation (no out-of-bounds access) following from invariant and guard. If mid is calculated as (lo + hi) // 2 in 32 bits, this is the sole proof line that stops holding.

Dijkstra’s Dutch national flag

Edsger Dijkstra posed the Dutch national flag problem: rearrange an array of three colored balls, without auxiliary memory and in one pass, so colors are grouped. Its numeric version partitions relative to pivot pp into smaller, equal and greater elements, central to three-way quicksort, which does not degrade with many duplicates.

lt, i, gt = 0, 0, len(a)
while i < gt:
    if a[i] < p:
        a[lt], a[i] = a[i], a[lt]; lt += 1; i += 1
    elif a[i] > p:
        gt -= 1; a[i], a[gt] = a[gt], a[i]
    else:
        i += 1

The invariant draws four regions: aj<pa_j < p for j<ltj < \mathit{lt}, aj=pa_j = p for lt≤j<i\mathit{lt} \le j < i, unexamined [i,gt)[i, \mathit{gt}), and aj>pa_j > p for j≥gtj \ge \mathit{gt}, with 0≤lt≤i≤gt≤n0 \le \mathit{lt} \le i \le \mathit{gt} \le n and the essential clause: a is a permutation of the original array. Without it, “set everything to pp” satisfies the rest. It is maintained because the body only swaps.

Prove maintenance branch by branch. If ai<pa_i < p, swap it with alta_{\mathit{lt}}, in the equal region (or aia_i itself if that region is empty); after advancing lt\mathit{lt} and ii, both regions remain correct. If ai=pa_i = p, advance ii. If ai>pa_i > p, swap with last unexamined element agt−1a_{\mathit{gt} - 1} and decrement gt\mathit{gt}; ii does not advance, because what arrives at ii has not been examined. That is the injected figure error: advancing ii puts an unchecked element in the equal region. The variant is gt−i\mathit{gt} - i, size of the unexamined region, decreasing exactly 1 per branch. On exit i=gti = \mathit{gt} and the unexamined region is empty.

Insertion sort: two loops, two invariants

for i in range(1, len(a)):
    key, j = a[i], i
    while j > 0 and a[j - 1] > key:
        a[j] = a[j - 1]
        j -= 1
    a[j] = key

Two nested loops have two invariants, the inner proving maintenance of the outer. The outer, at pass ii‘s head: prefix a0,…,ai−1a_0, \dots, a_{i-1} is a sorted permutation of the original prefix of length ii, and the rest of the array is untouched. This is the Cormen et al. version introducing invariants with insertion sort. Notice what it does not say: the prefix need not contain the ii smallest elements of the array. That is selection sort’s invariant, and false here.

The inner invariant describes the array with a hole at jj. If SS is the sorted prefix at the pass start, a0,…,aj−1a_0, \dots, a_{j-1} are S0,…,Sj−1S_0, \dots, S_{j-1} and aj+1,…,aia_{j+1}, \dots, a_i are Sj,…,Si−1S_j, \dots, S_{i-1}, all strictly greater than key. On exiting the inner loop either j=0j = 0 or aj−1≤a_{j-1} \le key; in both cases writing key in the hole yields a sorted prefix of length i+1i + 1. Variants are jj (inner) and n−in - i (outer). You will fill in details in a guided exercise.

Verified arithmetic

Divisibility and greatest common divisor

For integers a,ba, b not both zero, gcd⁡(a,b)\gcd(a, b) is the greatest integer dividing both; by convention gcd⁡(a,0)=∣a∣\gcd(a, 0) = \abs{a}. Euclid’s algorithm rests on a one-line lemma.

Proof

Let r=a mod br = a \bmod b, so a=qb+ra = qb + r for some integer qq; equivalently a≡r(modb)a \equiv r \pmod b, in the language of congruence modulo bb. If dd divides aa and bb, it divides r=a−qbr = a - qb. If dd divides bb and rr, it divides a=qb+ra = qb + r. Both pairs have exactly the same common divisors and therefore the same greatest one.

∎

Algorithm while b != 0: a, b = b, a % b has invariant gcd⁡(a,b)=gcd⁡(a0,b0)∧a,b≥0\gcd(a, b) = \gcd(a_0, b_0) \wedge a, b \ge 0, maintained by the lemma. Its variant is bb, because 0≤a mod b<b0 \le a \bmod b < b. On exit b=0b = 0 and a=gcd⁡(a,0)=gcd⁡(a0,b0)a = \gcd(a, 0) = \gcd(a_0, b_0).

Extended Euclid and Bézout’s identity

Tracking how each remainder is obtained from aa and bb proves something stronger than computing the gcd.

Bézout’s identity follows from an invariant. Extended Euclid (for a,b≥0a, b \ge 0) maintains rows (r0,s0,t0)(r_0, s_0, t_0) and (r1,s1,t1)(r_1, s_1, t_1), starts with (a,1,0)(a, 1, 0) and (b,0,1)(b, 0, 1) and, while r1≠0r_1 \ne 0, calculates q=⌊r0/r1⌋q = \lfloor r_0 / r_1 \rfloor and replaces rows with (r1,s1,t1)(r_1, s_1, t_1) and (r0−q r1, s0−q s1, t0−q t1)(r_0 - q\,r_1,\ s_0 - q\,s_1,\ t_0 - q\,t_1). The invariant is

r0=s0 a+t0 b ∧ r1=s1 a+t1 b ∧ gcd⁡(r0,r1)=gcd⁡(a,b) ∧ r0,r1≥0.r_0 = s_0\,a + t_0\,b \ \wedge\ r_1 = s_1\,a + t_1\,b \ \wedge\ \gcd(r_0, r_1) = \gcd(a, b) \ \wedge\ r_0, r_1 \ge 0.

Both linear equalities persist because the new row is an integer linear combination of the previous two, and a combination of combinations of aa and bb remains one. The gcd persists by the lemma. The variant is r1r_1. On exit r1=0r_1 = 0, so r0=gcd⁡(a,b)=s0 a+t0 br_0 = \gcd(a, b) = s_0\,a + t_0\,b. If aa or bb is negative, apply the algorithm to ∣a∣\abs{a} and ∣b∣\abs{b} and change the corresponding coefficient’s sign. The other claims are immediate. Since gcd⁡(a,b)\gcd(a, b) divides aa and bb, it divides every combination s′a+t′bs'a + t'b, so any positive combination, being a multiple of gcd⁡(a,b)\gcd(a, b), is at least gcd⁡(a,b)\gcd(a, b). Every common divisor of aa and bb divides s a+t b=gcd⁡(a,b)s\,a + t\,b = \gcd(a, b). You will complete the proof in exercises.

InteractiveEuclid as tiling with squares
a = 89555534211385
division 9 of 9
iirir_iqiq_isis_itit_isia+tibs_i a + t_i b
0891089
15510155
23411−134
3211−1221
41312−313
581−358
6515−85
731−8133
82113−212
912−21341
10055−890
89
55
Variant: the remainder… → 3 → 2 → 1 → 0
Bézout: r9r_{9}1 = −21·89 + 34·55
Divisions9
Lamé bound for this bb9
The last square has side gcd⁡(89,55)=1\gcd(89, 55) = 1 and the row before remainder 0 gives Bézout’s identity: 1=−21⋅89+34⋅551 = -21\cdot 89 + 34\cdot 55. This pair reaches Lamé’s bound: no divisor 5555 can require more divisions (the Fibonacci pair (89,55)(89, 55) reaches it first).
A rectangle a×ba \times b is covered with largest possible squares. Each Euclidean division, ri−1=qi ri+ri+1r_{i-1} = q_i\,r_i + r_{i+1}, places a strip of qiq_i squares of side rir_i and leaves a rectangle ri×ri+1r_i \times r_{i+1} (dashed). The final square has side gcd⁡(a,b)\gcd(a, b). The table accompanies each remainder with its Bézout coefficients and checks ri=sia+tibr_i = s_i a + t_i b live. With 89 × 55 every strip except the last has one square: the worst case. Compare 240 × 46 and 144 × 21.

The tiling visually proves the last side is the gcd. A square of side dd tiles a rectangle u×vu \times v if and only if dd divides uu and vv. The last square tiles the final rectangle, hence each earlier strip made of squares whose sides are multiples of it, and thus the whole rectangle. Conversely a square tiling the whole rectangle tiles each rectangle remaining after strips are removed. The greatest possible side is that of the final square.

Modular inverse

An integer aa has an inverse modulo mm if some uu satisfies a u≡1(modm)a\,u \equiv 1 \pmod m. Bézout gives both criterion and algorithm: if gcd⁡(a,m)=1\gcd(a, m) = 1, extended Euclid produces s a+t m=1s\,a + t\,m = 1, and reduction modulo mm gives s a≡1s\,a \equiv 1. The inverse is s mod ms \bmod m. If gcd⁡(a,m)=g>1\gcd(a, m) = g > 1, there is no inverse, because a u−1a\,u - 1 would be a multiple of mm and hence gg, while gg divides a ua\,u but not 1. This is the RSA step computing private exponent d≡e−1(modφ(N))d \equiv e^{-1} \pmod{\varphi(N)} from public exponent ee: in the classic example N=61⋅53N = 61 \cdot 53, φ(N)=3120\varphi(N) = 3120 and e=17e = 17, extended Euclid gives 17⋅(−367)+3120⋅2=117 \cdot (-367) + 3120 \cdot 2 = 1 and d=−367+3120=2753d = -367 + 3120 = 2753.

Number of divisions: Lamé’s theorem

Variant r1r_1 proves Euclid terminates but gives only a linear bound in bb. The truth is much better, with Fibonacci numbers as the worst case (F1=F2=1F_1 = F_2 = 1, Fk+2=Fk+1+FkF_{k+2} = F_{k+1} + F_k).

Proof

Induct on kk. If k=1k = 1, b≥1=F2b \ge 1 = F_2 and a>ba > b gives a≥2=F3a \ge 2 = F_3. Assume the result for kk and let (a,b)(a, b) need k+1k + 1 divisions. The first is a=qb+ra = qb + r with q≥1q \ge 1, and since more divisions remain r≥1r \ge 1; pair (b,r)(b, r), with b>r≥1b > r \ge 1, needs exactly kk. By induction b≥Fk+2b \ge F_{k+2} and r≥Fk+1r \ge F_{k+1}, so a=qb+r≥b+r≥Fk+2+Fk+1=Fk+3a = qb + r \ge b + r \ge F_{k+2} + F_{k+1} = F_{k+3}.

For the bound, Fk+1≥φk−1F_{k+1} \ge \varphi^{k-1} (by strong induction using φ2=φ+1\varphi^2 = \varphi + 1), hence φk−1≤b\varphi^{k-1} \le b. For digits, verify Fj+5≥10 FjF_{j+5} \ge 10\,F_j for j≥2j \ge 2. If bb has dd digits, Fk+1≤b<10d≤10dF2≤F5d+2F_{k+1} \le b < 10^d \le 10^d F_2 \le F_{5d+2}, and since FF increases, k+1<5d+2k + 1 < 5d + 2.

∎

The proof is induction on step count, strong induction in its most direct form. The bound is attained: pair (Fk+2,Fk+1)(F_{k+2}, F_{k+1}) needs exactly kk divisions, since each quotient except the last (F3/F2=2F_3 / F_2 = 2) is 1 and each remainder is the previous Fibonacci number. For (89,55)=(F11,F10)(89, 55) = (F_{11}, F_{10}) there are 9. It is the first pair needing kk divisions, as exhaustive search checks:

[ ]Fibonacci numbers are Euclid's worst caseBrowser
def divisiones(a, b):
    k = 0
    while b:
        a, b = b, a % b
        k += 1
    return k

N = 400
peor = {}
for a in range(2, N + 1):
    for b in range(1, a):
        k = divisiones(a, b)
        if k not in peor:
            peor[k] = (a, b)                          # el primer par (a mínimo) que necesita k divisiones
F = [0, 1]
while len(F) < 20:
    F.append(F[-1] + F[-2])
for k in sorted(peor):
    print(f"k = {k:2d}: primer par {str(peor[k]):11s} (F_(k+2), F_(k+1)) = ({F[k + 2]}, {F[k + 1]})")

For 64-bit integers b<264b < 2^{64} and log⁡φ264≈92.2\log_\varphi 2^{64} \approx 92.2: Euclid never needs more than 93 divisions. This helps explain why gcd is cheap enough for exact rationals, cryptography and fraction simplification in any CAS.

Fast exponentiation

Calculating an mod ma^n \bmod m with nn multiplications is infeasible for cryptographic exponents hundreds of digits long. Read nn in binary: a13=a8⋅a4⋅a1a^{13} = a^{8} \cdot a^{4} \cdot a^{1}, and obtain a,a2,a4,a8,…a, a^2, a^4, a^8, \dots by squaring.

r, b, e = 1 % m, a % m, n
while e > 0:
    if e % 2 == 1:
        r = r * b % m
    b = b * b % m
    e //= 2
return r

Initialization: (1 mod m)⋅(a mod m)n≡an(1 \bmod m) \cdot (a \bmod m)^n \equiv a^n, and 1 mod m1 \bmod m is in [0,m)[0, m). Maintenance: if ee is even, e=2e′e = 2e' and r⋅be=r⋅(b2)e′r \cdot b^{e} = r \cdot (b^2)^{e'}, what remains after b←b2b \leftarrow b^2, e←e′e \leftarrow e'. If ee is odd, e=2e′+1e = 2e' + 1 and r⋅be=(r b)⋅(b2)e′r \cdot b^e = (r\,b) \cdot (b^2)^{e'}. Reducing modulo mm after each product uses congruence’s compatibility with multiplication: if u≡u′u \equiv u' and v≡v′v \equiv v' modulo mm, then u v≡u′ v′u\,v \equiv u'\,v'. Exit: e=0e = 0 gives r≡anr \equiv a^n, and as 0≤r<m0 \le r < m, r=an mod mr = a^n \bmod m. The range clause seems pedantic, but initializing it requires 1 % m rather than 1: with m=1m = 1 and n=0n = 0, the naive version returns 1 instead of 0. Termination: e≥1e \ge 1 under the guard, and ⌊e/2⌋<e\lfloor e/2 \rfloor < e.

The number of passes is the number of bits of nn, ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1, with a multiplication per 1-bit and a square each pass. For n=1018n = 10^{18} this is 60 passes instead of a quintillion multiplications.

The argument uses nothing about modular arithmetic except associativity and an identity. It works in any monoid: with 2×22\times 2 matrices it computes FnF_n in O(log⁡n)\bigO(\log n) products, as in a linear recurrence’s companion matrix; with function composition it jumps 2k2^k automaton steps; with max⁡\max-plus it computes fixed-length graph paths.

Recursive algorithms

A recursive procedure has no loop, but the problem is the same: prove each call terminates and satisfies its specification, knowing only that its calls do so.

This is well-founded induction on μ\mu: the induction hypothesis is “ff is correct for every smaller-measure input,” exactly what is assumed for recursive calls. Termination is included, because an infinite call chain would give an infinite descending chain of measures. When recursion follows data structure (lists, trees, expressions), the measure is size and the method is the previous lesson’s structural induction.

This lesson’s examples have recursive versions with the same measure as their variants: gcd(a, b) = a if b == 0 else gcd(b, a % b) with μ=b\mu = b, and power pot(a, n) = 1 if n == 0 else pot(a * a, n // 2) * (a if n % 2 else 1) with μ=n\mu = n. Ackermann’s function,

A(0,n)=n+1,A(m+1,0)=A(m,1),A(m+1,n+1)=A(m,A(m+1,n)),A(0, n) = n + 1, \qquad A(m + 1, 0) = A(m, 1), \qquad A(m + 1, n + 1) = A(m, A(m + 1, n)),

terminates by lexicographic order on (m,n)(m, n): calls A(m,⋅)A(m, \cdot) decrease the first coordinate regardless of the second, and A(m+1,n)A(m + 1, n) decreases the second with the first fixed. It grows so fast (A(4,2)=265536−3A(4, 2) = 2^{65536} - 3, a 19,729-digit number) that it exceeds any function programmable using only for loops whose lengths are fixed before entry: it is not primitive recursive.

Implementation: executable invariants

An invariant written as an assertion turns each test into a proof check: if code and reasoning diverge, the program reports the exact pass. Instrument the variant similarly: save it before the body and afterward check it decreased and remains nonnegative.

[ ]Invariants and variants as assertionsBrowser
import random

def lower_bound(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        # invariante: a[j] < x para j < lo, a[j] >= x para j >= hi.
        # Como a está ordenado, basta con mirar las dos fronteras: O(1) por vuelta.
        assert 0 <= lo <= hi <= len(a)
        assert lo == 0 or a[lo - 1] < x
        assert hi == len(a) or a[hi] >= x
        v = hi - lo                                   # variante
        mid = lo + (hi - lo) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
        assert 0 <= hi - lo < v                       # baja y sigue siendo >= 0
    return lo

def insertion_sort(a):
    a = list(a)
    for i in range(1, len(a)):
        # invariante externo: a[:i] ordenado (la permutación la comprueba el test)
        assert all(a[k] <= a[k + 1] for k in range(i - 1))
        S, key, j = a[:i], a[i], i                    # S: el prefijo ordenado al entrar
        while j > 0 and a[j - 1] > key:
            # invariante interno: a[:j] == S[:j], a[j+1:i+1] == S[j:i] y todo S[j:i] > key
            assert a[:j] == S[:j] and a[j + 1:i + 1] == S[j:i]
            assert all(v > key for v in S[j:i])
            a[j] = a[j - 1]
            j -= 1                                    # variante: j
        a[j] = key
    return a

def dutch_flag(a, p):
    a = list(a)
    lt, i, gt = 0, 0, len(a)
    while i < gt:
        assert 0 <= lt <= i <= gt <= len(a)
        assert all(v < p for v in a[:lt]) and all(v == p for v in a[lt:i]) and all(v > p for v in a[gt:])
        v = gt - i                                    # variante
        if a[i] < p:
            a[lt], a[i] = a[i], a[lt]
            lt += 1; i += 1
        elif a[i] > p:
            gt -= 1
            a[i], a[gt] = a[gt], a[i]
        else:
            i += 1
        assert 0 <= gt - i < v
    return a, lt, gt

def ext_gcd(a, b):
    """Devuelve (g, s, t) con g = mcd(a, b) = s*a + t*b, para a, b >= 0."""
    r0, s0, t0 = a, 1, 0
    r1, s1, t1 = b, 0, 1
    while r1 != 0:
        assert r0 == s0 * a + t0 * b and r1 == s1 * a + t1 * b   # invariante
        q = r0 // r1
        v = r1                                                    # variante
        r0, s0, t0, r1, s1, t1 = r1, s1, t1, r0 - q * r1, s0 - q * s1, t0 - q * t1
        assert 0 <= r1 < v
    return r0, s0, t0

def pow_mod(a, n, m):
    """a**n mod m por cuadrados repetidos (n >= 0, m >= 1)."""
    r, b, e = 1 % m, a % m, n
    while e > 0:
        assert (r * pow(b, e, m)) % m == pow(a, n, m)  # invariante (pow solo como oráculo)
        v = e
        if e % 2 == 1:
            r = r * b % m
        b = b * b % m
        e //= 2
        assert 0 <= e < v
    return r

rnd = random.Random(0)
for _ in range(2000):
    a = sorted(rnd.randint(0, 20) for _ in range(rnd.randint(0, 15)))
    x = rnd.randint(-2, 22)
    k = lower_bound(a, x)
    assert all(v < x for v in a[:k]) and all(v >= x for v in a[k:])
    b = [rnd.randint(0, 9) for _ in range(rnd.randint(0, 12))]
    assert insertion_sort(b) == sorted(b)
    c, lt, gt = dutch_flag(b, 5)
    assert sorted(c) == sorted(b) and c[:lt] == [v for v in c if v < 5]
    u, w = rnd.randint(0, 10**6), rnd.randint(0, 10**6)
    g, s, t = ext_gcd(u, w)
    assert s * u + t * w == g
    assert pow_mod(rnd.randint(0, 10**9), rnd.randint(0, 10**6), rnd.randint(1, 10**9)) >= 0
print("2000 casos por algoritmo: todas las aserciones de invariante y variante se cumplen")
print("ext_gcd(240, 46) =", ext_gcd(240, 46), "  pow_mod(3, 200, 1000) =", pow_mod(3, 200, 1000))

Notice lower_bound assertions. The invariant has two array quantifiers; checking literally costs O(n)\bigO(n) per pass and makes search linear. Under the precondition (sorted array), “aj<xa_j < x for every j<loj < \mathit{lo}” is equivalent to “alo−1<xa_{\mathit{lo}-1} < x.” A good executable invariant uses the precondition to stay cheap and active in tests. The flag and insertion checks are complete because there is no structure to exploit; those assertions are for debugging, not production.

Assertions see only reachable states. Thousands of passing executions do not distinguish an inductive invariant from a merely true one, just like card 0 in the figure. Separate obligations by checking each over arbitrary states satisfying its hypotheses:

[ ]Checking each obligation separatelyBrowser
import random

def comprobar(nombre, inv, guarda, cuerpo, post, iniciales, muestra, n=20000, seed=1):
    """Prueba cada obligación por separado. El mantenimiento y la salida se prueban
    sobre estados aleatorios que cumplen el invariante, alcanzables o no."""
    rnd = random.Random(seed)
    fallo = {}
    for s in iniciales:                               # 1. inicialización
        if not inv(s):
            fallo.setdefault("inicialización", s)
    probados = {"mantenimiento": 0, "salida": 0}
    for _ in range(n):
        s = muestra(rnd)
        if not inv(s):
            continue
        if guarda(s):                                 # 2. mantenimiento: I y B => I tras el cuerpo
            probados["mantenimiento"] += 1
            t = cuerpo(dict(s))
            if not inv(t):
                fallo.setdefault("mantenimiento", (s, t))
        else:                                         # 3. salida: I y no B => Post
            probados["salida"] += 1
            if not post(s):
                fallo.setdefault("salida", s)
    print(f"{nombre}:  ({probados['mantenimiento']} estados con guarda, {probados['salida']} sin ella)")
    for ob in ("inicialización", "mantenimiento", "salida"):
        print(f"   {ob:15s}", "falla en " + str(fallo[ob]) if ob in fallo else "ok")

# Bucle 1:  i, j = 1, 0;  while i <= n: j += i; i += 1      Post: j >= 0
def cuerpo1(s):
    s["j"] += s["i"]; s["i"] += 1
    return s
ini1 = [{"i": 1, "j": 0, "n": n} for n in range(20)]
m1 = lambda r: {"i": r.randint(-10, 12), "j": r.randint(-5, 60), "n": r.randint(0, 10)}
for nombre, inv in [("j >= 0", lambda s: s["j"] >= 0),
                    ("j >= 0 and i >= 1", lambda s: s["j"] >= 0 and s["i"] >= 1)]:
    comprobar(nombre, inv, lambda s: s["i"] <= s["n"], cuerpo1, lambda s: s["j"] >= 0, ini1, m1)

# ¿y en las ejecuciones? j >= 0 vale en todas
ok = True
for n in range(50):
    i, j = 1, 0
    while i <= n:
        ok &= j >= 0
        j += i; i += 1
print("j >= 0 en todas las ejecuciones con n < 50:", ok)

# Bucle 2:  q, r = 0, a;  while r >= b: r -= b; q += 1      Post: a == q*b + r y 0 <= r < b
def cuerpo2(s):
    s["r"] -= s["b"]; s["q"] += 1
    return s
def m2(r):                                            # se construye a = q*b + r para cumplir la igualdad
    b, q, rr = r.randint(1, 6), r.randint(-3, 10), r.randint(-8, 12)
    return {"a": q * b + rr, "b": b, "q": q, "r": rr}
ini2 = [{"a": a, "b": b, "q": 0, "r": a} for a in range(20) for b in range(1, 6)]
post2 = lambda s: s["a"] == s["q"] * s["b"] + s["r"] and 0 <= s["r"] < s["b"]
for nombre, inv in [("a == q*b + r", lambda s: s["a"] >= 0 and s["a"] == s["q"] * s["b"] + s["r"]),
                    ("a == q*b + r and r >= 0", lambda s: s["a"] >= 0 and s["a"] == s["q"] * s["b"] + s["r"] and s["r"] >= 0)]:
    comprobar(nombre, inv, lambda s: s["r"] >= s["b"], cuerpo2, post2, ini2, m2)

Output reproduces the figure’s diagnoses: j≥0j \ge 0 holds in every execution but fails maintenance in a state with negative ii; a=qb+ra = qb + r is maintained but fails exit with negative rr. A technical detail determines whether the harness helps: sampling. An equality invariant like a=qb+ra = qb + r rarely holds in a random state, so m2 constructs satisfying states (choose bb, qq, rr and calculate aa). Property-based testing tools like Hypothesis use the same idea: generate by construction what filtering would almost always reject.

This check lies between tests and formal verification. A verifier such as Dafny or Why3 uses an SMT prover instead of random samples: for each loop annotated with invariant and variant, it generates the three obligations and termination as logical formulas and proves them for all states. The rules are next lesson’s Hoare logic.

The library version

FunctionWhat it doesNote
bisect.bisect_left(a, x)lower boundbisect_right gives the first kk with ak>xa_k > x
np.searchsorted(a, x, side="left")lower bound, vectorized over xrequires sorted a; does not check
math.gcd(a, b, ...)gcd of several integersPython 3.9 onward accepts more than two arguments
pow(a, n, m)fast modular exponentiationarbitrary-size integers
pow(a, -1, m)modular inversePython 3.8 onward; ValueError if absent
sympy.gcdex(a, b)extended Euclidreturns (s, t, g)
[ ]Compare with math.gcd, pow and bisectBrowser
import math, bisect, random
import numpy as np

rnd = random.Random(2)                                # ext_gcd, lower_bound y pow_mod: celda de las aserciones
for _ in range(3000):
    u, w = rnd.randint(0, 10**18), rnd.randint(0, 10**18)
    g, s, t = ext_gcd(u, w)
    assert g == math.gcd(u, w) and s * u + t * w == g
    a = sorted(rnd.randint(0, 50) for _ in range(rnd.randint(0, 30)))
    x = rnd.randint(-5, 55)
    assert lower_bound(a, x) == bisect.bisect_left(a, x) == int(np.searchsorted(a, x, side="left"))
print("ext_gcd coincide con math.gcd y lower_bound con bisect_left y np.searchsorted")

g, s, t = ext_gcd(17, 3120)
print(f"17·({s}) + 3120·({t}) = {g}  ->  inverso de 17 módulo 3120: {s % 3120}")
print("pow(17, -1, 3120) =", pow(17, -1, 3120))

a, n, m = 3, 10**18, 10**9 + 7
print("pow_mod(3, 10^18, 10^9 + 7) =", pow_mod(a, n, m), "  pow:", pow(a, n, m))
print("vueltas del bucle:", n.bit_length(), "  multiplicaciones por r:", bin(n).count("1"))
try:
    pow(6, -1, 9)
except ValueError as e:
    print("pow(6, -1, 9):", e)

Use the library versions: they are tested, faster and, for pow, handle arbitrary-size integers in C. Writing them teaches what they guarantee and assume. np.searchsorted does not check sortedness (which costs O(n)\bigO(n)) and returns a meaningless index without warning on unsorted input: the precondition is yours.

Common mistakes

Exercises

QuizWhich predicate works?
For k, p = 0, 1; while k < n: k = k + 1; p = 2 * p, with precondition n≥0n \ge 0 and postcondition p=2np = 2^n (all integer variables), which predicate is an inductive invariant implying the postcondition on exit?
QuizPartial or total
Consider while x != 0: x = x - 2, with integer xx and postcondition x=0x = 0. Which claims are true?

More than one answer may be correct.

QuizWhat decreases in subtraction Euclid?
In while x != y: if x > y: x = x - y else: y = y - x, with invariant x>0∧y>0x > 0 \wedge y > 0, which expressions are N\N-valued variants?

More than one answer may be correct.

NumericEuclid's worst case
How many divisions does Euclid perform on (a,b)=(89,55)(a, b) = (89, 55), including the final zero-remainder division?
NumericA modular inverse
Calculate the inverse of 17 modulo 3120, the unique d∈{0,…,3119}d \in \{0, \dots, 3119\} with 17 d≡1(mod3120)17\,d \equiv 1 \pmod{3120}.
NumericFast exponentiation passes
How many passes does the lesson's fast exponentiation loop (dividing ee by 2 each pass) take to compute a1000 mod ma^{1000} \bmod m?
ProofCorrectness of extended Euclid
Prove: For integers a,b≥0a, b \ge 0 not both zero, extended Euclid terminates and returns (r0,s0,t0)(r_0, s_0, t_0) with r0=gcd⁡(a,b)=s0 a+t0 br_0 = \gcd(a, b) = s_0\,a + t_0\,b.
0
The state is (r0,s0,t0,r1,s1,t1)(r_0, s_0, t_0, r_1, s_1, t_1), initially (a,1,0,b,0,1)(a, 1, 0, b, 0, 1). While r1≠0r_1 \neq 0, with q=⌊r0/r1⌋q = \lfloor r_0 / r_1 \rfloor, it becomes (r1,s1,t1,r0−qr1,s0−qs1,t0−qt1)(r_1, s_1, t_1, r_0 - q r_1, s_0 - q s_1, t_0 - q t_1).

Step 1 of 5. Which invariant do you choose?

ProofTotal correctness of insertion sort
Prove: Insertion sort (the lesson's shifting version) terminates and leaves the array as a sorted permutation of the original.
0
Call the original array AA and its length nn. The outer loop traverses i=1,…,n−1i = 1, \dots, n - 1; the inner shifts elements greater than key right, leaving a hole at position jj.

Step 1 of 4. What is the outer-loop invariant at the head of pass ii?

ProofTermination with lexicographic order
Prove: A loop on naturals (x,y)(x, y), while x>0x > 0 or y>0y > 0, each pass either (if x>0x > 0) decrements xx and assigns yy an arbitrary natural, or (if y>0y > 0) decrements yy. It always terminates regardless of actions and values chosen.
0
The body is nondeterministic: prove no infinite execution exists.

Step 1 of 4. Which measure do you use?

CodeLower bound with invariant and variant
Implement lower_bound(a, x), returning the first index i with a[i] >= x (or len(a) if none exists) for a nondecreasing array a. Write the invariant and variant as assertions inside the loop (at least two assert). Search must remain logarithmic with assertions active: a test counts array reads. Do not use bisect.
def lower_bound(a, x):
  """Primer índice i con a[i] >= x (len(a) si no hay ninguno). a está ordenado."""
  lo, hi = 0, len(a)
  while lo < hi:
      # escribe aquí el invariante y la variante como aserciones
      mid = (lo + hi) // 2
      # completa la actualización de lo o de hi
      break
  return lo
Shift+Enter to run

Summary

Key idea
A loop is proved with an inductive invariant, initialized, maintained by one isolated pass from any state satisfying it, and implying the postcondition with a false guard; and a variant decreasing each pass in a well-founded order. The former gives partial correctness; the latter termination.
  • Partial correctness says “if it terminates, the result is correct”; total correctness adds termination. They are proved separately.
  • Maintenance is required for every state satisfying invariant and guard, not only reachable states. A predicate true in all executions may not be inductive and must be strengthened like an induction hypothesis.
  • Find invariants from postconditions: remove a conjunct, replace a constant by a variable, or draw array regions. Exit fixes the form.
  • A N\N-valued variant suffices for most loops; lexicographic order proves termination no natural variant can. No variant is known for Collatz.
  • Extended Euclid proves Bézout’s identity with invariant ri=si a+ti br_i = s_i\,a + t_i\,b, gives a modular inverse and, by Lamé’s theorem, never uses more divisions than a pair of consecutive Fibonacci numbers.
  • Fast exponentiation maintains r be≡anr\,b^e \equiv a^n and takes as many passes as nn has bits; it works in any monoid.
  • Recursive algorithms are proved by well-founded induction on an argument measure, giving correctness and termination together.
  • Proofs are relative to a model: overflow in (lo + hi) / 2 and floating-point rounding lie outside integer and real models. Invariants as assertions and randomized checking of each obligation bring proof closer to real code.