Discrete MathematicsAlgorithms and Growth of Functions4 of 4
Algorithms and Growth of Functions · 4
Loop Invariants and Proving Algorithms Correct
Testing an algorithm on sample inputs only shows that it works for the numbers we tried, so we need a way to prove that a loop gives the right answer for every valid input.
1
What a Loop Invariant Is
A loop invariant is a statement about an algorithm's variables that is true right before the loop checks its condition on every lap, including the final check when the loop exits.
To find the largest number in a list A[0…n−1] of n≥1 numbers, consider this loop:
Treating the index i as a divider between the checked slice A[0…i−1] and the unchecked slice A[i…n−1] gives the loop invariant at the snapshot point:
max_so_far=max(A[0…i−1])and1≤i≤n
Partway through the list, max_so_far is not yet the maximum of the whole list, but for every position of the divider i it is the maximum of the checked slice A[0…i−1] to the left. When the divider reaches i=n, that slice is the entire list.
Wherever the divider stops, `max_so_far` is the largest number to its left, so when the divider reaches the end, `max_so_far` is the largest number in the whole list.
2
The Four-Step Correctness Proof
Spotting a loop invariant shows why the answer should be right at the end, but we still need to prove that the invariant holds on every lap and that the loop actually stops. We prove our max_so_far loop correct for any list A[0…n−1] with n≥1 by induction across the snapshots, followed by a monovariant check that the loop terminates.
The Four-Step Correctness Proof
Text solution
Step 1: Initialization (true before the first lap)Before the loop runs, the setup sets the divider to i=1 with n≥1, so the slice to the left of the divider has only the single element A[0].
max_so_far=A[0]=max(A[0…0])and1≤1≤n
Step 2: Maintenance (preserved across one lap)Assuming the invariant holds at the top of a lap where i<n, comparing A[i] against max_so_far makes max_so_far the maximum of A[0…i] right before i increases to inew=i+1.
Step 3: Payoff (invariant plus exit condition gives the answer)The loop exits only when i<n becomes false, which combines with the invariant bound i≤n to force the divider to n.
i≥n and 1≤i≤n⟹i=n⟹max_so_far=max(A[0…n−1])
Step 4: Termination (a monovariant runs out)The number of unchecked elements n−i starts at the non-negative integer n−1 and strictly decreases by 1 on every lap, so it cannot stay positive forever.
n−inew=n−(i+1)=(n−i)−1≥0
So the loop must terminate, and when it does, max_so_far holds the maximum of the entire list A[0…n−1].
These four steps separate proving the answer is right from proving the loop stops:
Total Correctness (stops and is right)Initialization+Maintenance+Payoff⎭⎬⎫Partial Correctness(right if it stops)+Termination
3
Finding an Invariant Without a List
When a loop updates numbers without a list, there is no array index to use as a sliding divider. For non-negative integers A≥0 and B≥0, we want to find the loop invariant for multiplying A and B by repeated addition:
Writing out a few snapshots shows that what has already been added into total and what remains to be added always add up to the full product:
work donetotal+work leftA⋅count=whole jobA⋅B
On every lap, adding A to total and subtracting 1 from count moves one A from the work left (A⋅count) into the work done (total), keeping their sum fixed at A⋅B until count=0.
Each step shifts one chunk from work left into work done, keeping the combined amount fixed at the full product.
4
Broken and Weak Invariants
Not every true-looking statement about a loop's variables can prove the algorithm works. For the multiplication loop with A,B≥0, we want to check whether a proposed statement stays true on every lap and whether it carries enough information to force total=A⋅B on exit.
Broken and Weak Invariants
A candidate invariant can fail in two different places:
Fails Maintenance (breaks on a later lap): The guess total≤A holds at the start (total=0≤A) and even after one lap (total=A≤A), but when A>0 and B≥2, the second lap breaks it:
totalnew=A+A=2A>A
Fails Payoff (too weak at the finish line): The statement total≥0 and count≥0 holds at the start and stays true on every lap, so it is a genuine loop invariant, but on exit it only tells us total≥0.
Strengthened invariant: Pairing the accounting equation with the counter bound count≥0 lets the exit condition count≤0 force count=0 and give us the answer:
Now we can combine an accounting equation with an inequality bound in a full four-step proof. Given integers N≥0 and d>0, we want to prove Total Correctness for finding the quotient q and remainder r by repeated subtraction:
r=Nq=0while r≥d:r=r−dq=q+1
Specifically, we want to prove that the loop terminates with N=d⋅q+r and 0≤r<d.
Proving Division by Repeated Subtraction
Text solution
Invariant (work done plus work left, with the remainder bound)The amount subtracted so far (d⋅q) plus the remainder left (r) equals N, and the remainder stays non-negative.
N=d⋅q+randr≥0
Step 1: Initialization (before the first lap)Setting r=N and q=0 satisfies both parts of the invariant because N≥0.
d⋅q+r=d⋅0+N=Nandr=N≥0
Step 2: Maintenance (across one lap when r≥d)Adding 1 to q and subtracting d from r cancel out in the sum, while the loop condition r≥d guarantees that the new remainder is non-negative.
d⋅qnew+rnew=d(q+1)+(r−d)=d⋅q+d+r−d=d⋅q+r=N
r≥d⟹rnew=r−d≥0
Step 3: Payoff (when r≥d becomes false)Exiting the loop means r<d, which combines with the invariant to give the complete division condition.
N=d⋅q+rand0≤r<d
Step 4: Termination (the remainder runs out)Because d≥1 is a positive integer, the non-negative integer r strictly decreases by at least 1 on every lap and must eventually drop below d.
rnew=r−d≤r−1<r
So the algorithm always terminates with integers q and r satisfying N=d⋅q+r and 0≤r<d.
6
Proving Recursive Algorithms by Induction
When an algorithm repeats work by calling itself on a smaller input rather than running a `while` loop, we don't need a loop invariant. We prove a recursive algorithm directly by mathematical induction on the input size n. For any real number a and integer n≥0, we want to prove that this recursive function terminates and returns an:
Base Case (n=0)When n=0, the `if n == 0` branch runs immediately without making a recursive call and returns 1.
power(a,0)=1=a0
Inductive Hypothesis (n=k)Assume that for some integer k≥0,power(a,k) terminates and returns ak.
power(a,k)=ak
Inductive Step (n=k+1)Since k+1≥1=0, the `else` branch runs and calls power(a,k), which we replace using the inductive hypothesis.
power(a,k+1)=a⋅ak by IHpower(a,k)=a⋅ak=ak+1
So by mathematical induction, power(a,n) terminates and returns an for all integers n≥0.
When a recursive call shrinks the input by halving (such as ⌊2n⌋) instead of stepping down to n−1, use strong induction and assume the function works for all smaller inputs 0≤j<n.
Key concepts
Before starting a correctness proof, look at how the algorithm repeats its work. If the algorithm is recursive with no loop, skip loop invariants entirely and prove it by induction on the input size n: use ordinary induction when the recursive call steps from n to n−1 (as in power(a,n−1)), and switch to strong induction assuming 0≤j<n whenever the call jumps to a smaller input like 2n or 2n−1.
If the algorithm is a loop, pick the invariant from what the loop updates and always include the inequality bound needed at the exit:
Looping over a list A[0…n−1]
Treat the counter i as a divider and state that the running variable is right for the checked slice A[0…i−1] to the left, paired with 1≤i≤n (or 0≤i≤n if i starts at 0), such as max_so_far=max(A[0…i−1]) and 1≤i≤n.
Looping over numbers without a list
Write an accounting equation where work done plus work left equals the whole job, paired with non-negativity of the decreasing quantity, such as total+A⋅count=A⋅B with count≥0, or N=d⋅q+r with r≥0.
Once you have the invariant, run the four steps. Check Initialization before the first lap, Maintenance across one lap assuming the loop condition holds, and Payoff by combining the invariant with the false loop condition at exit (which completes Partial Correctness). Then prove Termination for Total Correctness by naming an integer monovariant (n−i,count, or r) that starts non-negative and drops by at least 1 on every lap.
7
Practice
1
For non-negative integers x≥0 and y≥0, consider the loop `a = x; b = y; while b > 0: { a = a + 2; b = b - 1 }`, which is intended to terminate with a=x+2y. Four candidate loop invariants are proposed: (a) a=x+2 (b) a≤x+2 (c) a≥x and b≥0 (d) a+2b=x+2y and b≥0 For each candidate, state whether it fails Step 1 (Initialization), passes Step 1 but fails Step 2 (Maintenance), passes Steps 1 and 2 as a true invariant but fails Step 3 (Payoff) by being too weak, or succeeds in proving a=x+2y on exit.
Test each candidate at the starting values a=x and b=y first, then across a general lap (not just Lap 1), and finally check whether setting b=0 forces a=x+2y.
(a) Fails Step 1 (Initialization)Before the loop starts, a=x=x+2.
(b) Passes Step 1, but fails Step 2 (Maintenance)At the start, a=x≤x+2 holds. (Watch out: checking only the first lap gives a=x+2≤x+2, which makes (b) look like a valid invariant, but when y≥2 the second lap sets a=x+4>x+2.)
(c) Passes Steps 1 and 2 as a true loop invariant, but fails Step 3 (Payoff) because it is too weakAt the start a=x≥x and b=y≥0, and each lap with b>0 (so integer b≥1) preserves a+2≥x and b−1≥0. However, on exit b≤0 and b≥0 give b=0, leaving only a≥x, which does not force a=x+2y.
(d) Succeeds in proving a=x+2y on exit
Initialization: At a=x and b=y,a+2b=x+2y and b=y≥0.
Maintenance: In a lap where b>0 (so b≥1), (a+2)+2(b−1)=a+2b=x+2y and b−1≥0.
Payoff: On exit, b≤0 and b≥0 force b=0, which gives a+2(0)=x+2y, so a=x+2y.
2
Given a list A[0…n−1] of n≥0 numbers, consider the algorithm `s = 0; i = 0; while i < n: { s = s + A[i]; i = i + 1 }`. Using the convention that the empty sum from j=0 to −1 is 0, write the sliding-divider loop invariant and give a four-step Total Correctness proof that the algorithm terminates with s=A[0]+A[1]+⋯+A[n−1].
At the top of the loop, the divider sits at index i; which indices j have already been added into s, and what bounds must the integer i satisfy?
Invariants=∑j=0i−1A[j] and 0≤i≤n (for integer i). (Watch out: writing the upper limit as i instead of i−1 gives s=∑j=0iA[j], which fails Step 1 at i=0 because s=0 while ∑j=00A[j]=A[0].)
Step 1 (Initialization)Before the loop, s=0 and i=0. The sum to the left of the divider is the empty sum ∑j=0−1A[j]=0=s, and since n≥0,0≤0≤n holds.
Step 2 (Maintenance)Assume at the start of a lap that s=∑j=0i−1A[j],0≤i≤n, and i<n. After the loop body runs, snew=s+A[i]=∑j=0i−1A[j]+A[i]=∑j=0iA[j] and inew=i+1. Rewriting i as inew−1 gives snew=∑j=0inew−1A[j], and since i and n are integers with 0≤i<n,1≤inew≤n, so 0≤inew≤n.
Step 3 (Payoff)On exit, i<n is false, so i≥n. Combined with 0≤i≤n, this forces i=n, and substituting i=n into the invariant gives s=∑j=0n−1A[j].
Step 4 (Termination)The monovariant n−i starts at n≥0, is an integer that strictly decreases by 1 on every lap, and cannot drop below 0 while i<n holds, so the loop must terminate.
3
For a non-zero real number a and a non-negative integer b≥0, consider the algorithm `p = 1; k = b; while k > 0: { p = p * a; k = k - 1 }`. State a loop invariant connecting p and k to ab, and give a four-step Total Correctness proof that the algorithm terminates with p=ab.
Because the loop multiplies by a each lap, connect the product accumulated in p and the k factors of a still left to multiply so their product equals ab.
Invariantp⋅ak=ab and k≥0 (for integer k). (Watch out: writing an additive equation p+ak=ab fails Step 1 because 1+ab=ab, and leaving out k≥0 leaves only k≤0 at exit instead of forcing k=0.)
Step 1 (Initialization)Before the loop, p=1 and k=b, so p⋅ak=1⋅ab=ab and k=b≥0.
Step 2 (Maintenance)Assume p⋅ak=ab and k≥0 at the top of the loop, and that the loop condition k>0 holds (so k≥1 because k is an integer). After one lap, pnew=p⋅a and knew=k−1. Then pnew⋅aknew=(p⋅a)⋅ak−1=p⋅ak=ab, and k≥1 implies knew=k−1≥0.
Step 3 (Payoff)When the loop stops, k>0 is false, so k≤0. Combined with k≥0, this forces k=0, and substituting k=0 into p⋅ak=ab gives p⋅a0=p=ab.
Step 4 (Termination)The monovariant k starts at the non-negative integer b≥0, stays a non-negative integer, and strictly decreases by 1 each lap, so it must reach 0 and terminate the loop.
4
For non-negative integers A≥0 and B≥0, consider the Russian Peasant Multiplication loop `total = 0; x = A; y = B; while y > 0: { if y is odd then total = total + x; x = 2 * x; y = ⌊y / 2⌋ }`. Using the loop invariant total+x⋅y=A⋅B and y≥0, prove Total Correctness that the loop terminates with total=A⋅B.
In Step 2 (Maintenance), split into two cases based on whether y is even (y=2m) or odd (y=2m+1), and write ⌊2y⌋ in terms of y in each case.
Step 1 (Initialization)Initially total=0,x=A, and y=B, so total+x⋅y=0+A⋅B=A⋅B and y=B≥0.
Step 2 (Maintenance)Assume total+x⋅y=A⋅B,y≥0, and the loop condition y>0 holds (so integer y≥1).
Case 1 (y is even):y=2m for an integer m≥1, so ⌊2y⌋=m=2y. The `if` branch does not run, giving totalnew=total,xnew=2x, and ynew=2y. Then totalnew+xnew⋅ynew=total+(2x)(2y)=total+x⋅y=A⋅B and ynew=m≥0.
Case 2 (y is odd):y=2m+1 for an integer m≥0, so ⌊2y⌋=m=2y−1.(Watch out: writing ynew=2y instead of 2y−1 when y is odd gives (total+x)+(2x)(2y)=A⋅B+x, making the invariant appear to fail by +x.) The `if` branch runs, giving totalnew=total+x,xnew=2x, and ynew=2y−1. Then totalnew+xnew⋅ynew=(total+x)+(2x)2y−1=total+x+x(y−1)=total+x⋅y=A⋅B and ynew=m≥0.
Step 3 (Payoff)On exit, y≤0 and y≥0 force y=0, so total+x⋅0=A⋅B, giving total=A⋅B.
Step 4 (Termination)The monovariant y starts at B≥0 and remains a non-negative integer; on every lap y≥1, so ynew=⌊2y⌋≤2y<y, meaning y strictly decreases by at least 1 each lap and must reach 0.
5
Consider the recursive algorithm `function sq(n): if n == 0: return 0; else: return sq(n - 1) + 2*n - 1`. Prove by mathematical induction that for all integers n≥0, `sq(n)` terminates and returns n2.
In the inductive step for n=k+1, substitute k+1 for every n in the `else` branch before applying the inductive hypothesis to `sq(k)`.
Base Case (n=0)When n=0, the condition `n == 0` is true, so `sq(0)` immediately terminates and returns 0=02.
Inductive HypothesisSuppose that for some integer k≥0, `sq(k)` terminates and returns k2.
Inductive Step (n=k+1)Since k≥0,k+1≥1=0, so `sq(k + 1)` takes the `else` branch and evaluates sq((k+1)−1)+2(k+1)−1=sq(k)+2k+1.(Watch out: forgetting to plug k+1 into 2n−1 leaves sq(k)+2k−1=k2+2k−1 instead of (k+1)2.) By the inductive hypothesis, `sq(k)` terminates and returns k2. Substituting k2 for `sq(k)`, `sq(k + 1)` terminates and returns k2+2k+1=(k+1)2. By induction, `sq(n)` terminates and returns n2 for all integers n≥0.
6
Consider the recursive algorithm `function mult(a, n): if n == 0: return 0; else if n is even: return 2 mult(a, n / 2); else: return a + 2 mult(a, (n - 1) / 2)`. Prove by strong induction that for any real number a and all integers n≥0, `mult(a, n)` terminates and returns a⋅n.
For n=k≥1, assume the claim holds for all integers j with 0≤j<k, then check both the even and odd branches to verify that the recursive input is an integer in that range.
Base Case (n=0)When n=0, `n == 0` is true, so `mult(a, 0)` immediately terminates and returns 0=a⋅0.
Strong Inductive HypothesisLet k≥1 be an integer and assume that for every integer j with 0≤j<k, `mult(a, j)` terminates and returns a⋅j.(Watch out: assuming the claim only for k−1 cannot handle the recursive calls at 2k or 2k−1, and in each branch you must verify that the recursive argument is an integer satisfying 0≤j<k.)
Inductive Step (n=k)Since k≥1=0, the base-case branch does not run.
Case 1 (k is even): The second branch calls `mult(a, k / 2)`. Since k≥2 is an even integer, 2k is an integer with 0≤2k<k. By the strong inductive hypothesis, `mult(a, k / 2)` terminates and returns a⋅2k, so `mult(a, k)` terminates and returns 2⋅(a⋅2k)=a⋅k.
Case 2 (k is odd): The `else` branch calls `mult(a, (k - 1) / 2)`. Since k≥1 is an odd integer, 2k−1 is an integer with 0≤2k−1<k. By the strong inductive hypothesis, `mult(a, (k - 1) / 2)` terminates and returns a⋅2k−1, so `mult(a, k)` terminates and returns a+2⋅(a⋅2k−1)=a+a(k−1)=a⋅k.
By strong induction, `mult(a, n)` terminates and returns a⋅n for all integers n≥0.