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 elements, low + high can exceed 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.
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 ,” 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 , find the lower bound of : the first index with , or if none exists. This is the basic binary-search operation (bisect_left in Python, lower_bound in C++), answering “is present?”, “where should it be inserted?” and “how many elements are below ?”
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 . From hi to the end everything is at least . 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.
The figure’s three bugs fail in different ways, corresponding to different proof obligations:
- With
hi = mid - 1, for step three setshi = 3when : 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. - With
lo = midthe invariant never breaks (saying everything beforemidis less than is weaker than saying so throughmid, and remains true). But when the unknown region has one cell and it is less than ,lodoes not move. Only termination fails: the program is partially correct but never returns. - With guard
lo <= hi, the loop enters with an empty unknown region. Iflo = hi < n,mid = loandhi = midchanges nothing: no termination again. Iflo = hi = n, it readsa[n]outside the array. The guard must ensure the unknown region is nonempty, the only waymidis a valid index and varianthi - lodecreases.
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 the caller promises to satisfy, and a postcondition the program promises to establish. For lower bound, says a is nondecreasing and says result satisfies , for every , and for every .
Write to say fragment satisfies specification . 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 under any precondition: if it terminates, the guard is false, hence . But it is totally correct only if the precondition ensures is even and nonnegative; with it traverses 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 assigns every variable a value; denotes the state set. The guard is a predicate on and the body, if deterministic, is a function . An execution from is the sequence
which stops at the first with . The loop terminates from if that exists. The reachable states are all from executions beginning in states satisfying . If the body is nondeterministic (chooses among actions), is a relation and everything below holds by requiring conditions for every possible successor.
Loop invariants
Proof
Fix an execution beginning after Init from a state satisfying . Prove by induction on for every through the end of execution. For this is initialization. If and execution continues, holds, and maintenance gives . If execution ends at , then , and with exit gives .
The proof is textbook induction; what matters is what makes it possible. Maintenance is required for every state satisfying , 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 (), 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
is true in every execution and implies the postcondition. But it is not inductive: state , , satisfies and the guard, and after one pass gives . That state is unreachable because starts at 1 and only increases. But hypothesis “” 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 suffices and is maintained: if and , then and .
There is always an inductive invariant implying any invariant property: the reachable set itself, closed under inside by definition. The problem is that rarely has a manageable description. Proving a loop means finding a predicate between and the desired property that is both inductive and expressible.
The four loops cover four diagnoses:
- Too strong. In integer division, is exactly the postcondition and fails initialization: on entry can be at least (the box gives smallest case ).
- Too weak. initializes and is maintained (subtracting from and adding 1 to does not change ), but exit yields only , and state , , , satisfies the invariant and false guard without satisfying the postcondition. is missing.
- True but not inductive. in the preceding loop.
- Correct. for division; 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 must imply .
Weaken the postcondition by removing a conjunct. If and easily becomes a negated guard, take and . In integer division, is . Remove : the invariant is and guard . On exit the false guard restores the missing conjunct.
Replace a constant with a variable. If mentions constant , introduce moving from an endpoint to and write with instead of . For a sum, is and the invariant , with guard . Bound is not decorative: without it, exit gives only and the figure’s box finds state , , . Forgetting index ranges is the most common oversight.
Divide the array into regions. When quantifies over an array (“everything left of is less than ”), 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 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 from a state satisfying . The loop rule gives for all , and since execution does not stop, for all . Then is an infinite descending chain in , contradicting well-foundedness of .
∎For lower bound, : under the invariant it is , and under guard we have , so both and reduce it. The variant needs the invariant (to know it is ) and guard (to know it decreases). With lo = mid, the calculation fails exactly when , that is, .
Two cautions about . First, it must be well-founded: decreasing alone is insufficient. Over reals, while x > 0: x = x / 2 decreases every pass and never terminates. In floating point it does terminate after 1075 passes if starts at 1, because rounds to 0; a reason the mathematical model does not cover, just as the midpoint overflowed for an unmodeled reason. Second, does not always suffice.
Lexicographic orders
Consider a loop on two naturals that each pass either decrements and assigns an arbitrary natural (chosen by a user, network or random generator), or decrements . Neither nor is a variant: the former does not decrease when does, the latter increases when jumps. What always decreases is the pair in lexicographic order:
Lexicographic order on is well-founded. In a descending chain first coordinates form a nonincreasing sequence of naturals, eventually stabilizing; thereafter second coordinates strictly decrease in forever, impossible. The argument extends to for any , and proves termination of Ackermann’s function or a parser alternating between consuming input and reducing a stack.
This loop admits no -valued variant. If decreased each step, chain would require , and step would require for every . No natural exceeds all naturals. Lexicographic order is not just convenient: it is strictly more powerful.
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 : 27 takes 111 steps and rises to 9232 before falling, and computer verification covers at least all (Barina, 2021). But no variant function is known, and termination for all 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 and , the range holds and both quantifiers range over empty sets.
Maintenance. Assume and . Then satisfies , so exists. If , every has by sorting, so new satisfies the second clause; the others stay unchanged. If , every has , and new satisfies the third.
Exit. and give , and the quantified clauses with give the postcondition. is unique: if both satisfied it, would be both and .
Termination. Under , and both branches reduce it: and .
∎The proof gives more than correctness. Each pass leaves at most unknown elements, so there are at most passes. And “ 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 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: for , for , unexamined , and for , with and the essential clause: a is a permutation of the original array. Without it, “set everything to ” satisfies the rest. It is maintained because the body only swaps.
Prove maintenance branch by branch. If , swap it with , in the equal region (or itself if that region is empty); after advancing and , both regions remain correct. If , advance . If , swap with last unexamined element and decrement ; does not advance, because what arrives at has not been examined. That is the injected figure error: advancing puts an unchecked element in the equal region. The variant is , size of the unexamined region, decreasing exactly 1 per branch. On exit 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 ‘s head: prefix is a sorted permutation of the original prefix of length , 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 smallest elements of the array. That is selection sort’s invariant, and false here.
The inner invariant describes the array with a hole at . If is the sorted prefix at the pass start, are and are , all strictly greater than key. On exiting the inner loop either or key; in both cases writing key in the hole yields a sorted prefix of length . Variants are (inner) and (outer). You will fill in details in a guided exercise.
Verified arithmetic
Divisibility and greatest common divisor
For integers not both zero, is the greatest integer dividing both; by convention . Euclid’s algorithm rests on a one-line lemma.
Proof
Let , so for some integer ; equivalently , in the language of congruence modulo . If divides and , it divides . If divides and , it divides . 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 , maintained by the lemma. Its variant is , because . On exit and .
Extended Euclid and Bézout’s identity
Tracking how each remainder is obtained from and proves something stronger than computing the gcd.
Bézout’s identity follows from an invariant. Extended Euclid (for ) maintains rows and , starts with and and, while , calculates and replaces rows with and . The invariant is
Both linear equalities persist because the new row is an integer linear combination of the previous two, and a combination of combinations of and remains one. The gcd persists by the lemma. The variant is . On exit , so . If or is negative, apply the algorithm to and and change the corresponding coefficient’s sign. The other claims are immediate. Since divides and , it divides every combination , so any positive combination, being a multiple of , is at least . Every common divisor of and divides . You will complete the proof in exercises.
The tiling visually proves the last side is the gcd. A square of side tiles a rectangle if and only if divides and . 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 has an inverse modulo if some satisfies . Bézout gives both criterion and algorithm: if , extended Euclid produces , and reduction modulo gives . The inverse is . If , there is no inverse, because would be a multiple of and hence , while divides but not 1. This is the RSA step computing private exponent from public exponent : in the classic example , and , extended Euclid gives and .
Number of divisions: Lamé’s theorem
Variant proves Euclid terminates but gives only a linear bound in . The truth is much better, with Fibonacci numbers as the worst case (, ).
Proof
Induct on . If , and gives . Assume the result for and let need divisions. The first is with , and since more divisions remain ; pair , with , needs exactly . By induction and , so .
For the bound, (by strong induction using ), hence . For digits, verify for . If has digits, , and since increases, .
∎The proof is induction on step count, strong induction in its most direct form. The bound is attained: pair needs exactly divisions, since each quotient except the last () is 1 and each remainder is the previous Fibonacci number. For there are 9. It is the first pair needing divisions, as exhaustive search checks:
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 and : 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 with multiplications is infeasible for cryptographic exponents hundreds of digits long. Read in binary: , and obtain 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: , and is in . Maintenance: if is even, and , what remains after , . If is odd, and . Reducing modulo after each product uses congruence’s compatibility with multiplication: if and modulo , then . Exit: gives , and as , . The range clause seems pedantic, but initializing it requires 1 % m rather than 1: with and , the naive version returns 1 instead of 0. Termination: under the guard, and .
The number of passes is the number of bits of , , with a multiplication per 1-bit and a square each pass. For 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 matrices it computes in products, as in a linear recurrence’s companion matrix; with function composition it jumps automaton steps; with -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 : the induction hypothesis is “ 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 , and power pot(a, n) = 1 if n == 0 else pot(a * a, n // 2) * (a if n % 2 else 1) with . Ackermann’s function,
terminates by lexicographic order on : calls decrease the first coordinate regardless of the second, and decreases the second with the first fixed. It grows so fast (, 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.
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 per pass and makes search linear. Under the precondition (sorted array), “ for every ” is equivalent to “.” 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:
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: holds in every execution but fails maintenance in a state with negative ; is maintained but fails exit with negative . A technical detail determines whether the harness helps: sampling. An equality invariant like rarely holds in a random state, so m2 constructs satisfying states (choose , , and calculate ). 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
| Function | What it does | Note |
|---|---|---|
bisect.bisect_left(a, x) | lower bound | bisect_right gives the first with |
np.searchsorted(a, x, side="left") | lower bound, vectorized over x | requires sorted a; does not check |
math.gcd(a, b, ...) | gcd of several integers | Python 3.9 onward accepts more than two arguments |
pow(a, n, m) | fast modular exponentiation | arbitrary-size integers |
pow(a, -1, m) | modular inverse | Python 3.8 onward; ValueError if absent |
sympy.gcdex(a, b) | extended Euclid | returns (s, t, g) |
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 ) and returns a meaningless index without warning on unsorted input: the precondition is yours.
Common mistakes
Exercises
k, p = 0, 1; while k < n: k = k + 1; p = 2 * p, with precondition and postcondition (all integer variables), which predicate is an inductive invariant implying the postcondition on exit?while x != 0: x = x - 2, with integer and postcondition . Which claims are true?More than one answer may be correct.
while x != y: if x > y: x = x - y else: y = y - x, with invariant , which expressions are -valued variants?More than one answer may be correct.
Step 1 of 5. Which invariant do you choose?
Step 1 of 4. What is the outer-loop invariant at the head of pass ?
Step 1 of 4. Which measure do you use?
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 loSummary
- 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 -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 , gives a modular inverse and, by Lamé’s theorem, never uses more divisions than a pair of consecutive Fibonacci numbers.
- Fast exponentiation maintains and takes as many passes as 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) / 2and floating-point rounding lie outside integer and real models. Invariants as assertions and randomized checking of each obligation bring proof closer to real code.