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.

max_so_far=A[0]\text{max\_so\_far} = A[0]
i=1i = 1
snapshot\htmlClass{lc-pink}{\text{snapshot}}
i<n ?i < n\,?
yes\text{yes}
if A[i]>max_so_far:\text{if } A[i] > \text{max\_so\_far}\text{:}
max_so_far=A[i]\quad \text{max\_so\_far} = A[i]
i=i+1i = i + 1
no\htmlClass{lc-orange}{\text{no}}
exit\text{exit}

To find the largest number in a list A[0…n−1]A[0 \dots n - 1] of n≥1\given{n \ge 1} numbers, consider this loop:

max_so_far=A[0]i=1while i<n:if A[i]>max_so_far:max_so_far=A[i]i=i+1\displaystyle \begin{aligned} &\text{max\_so\_far} = A[0] \\ &i = 1 \\ &\text{while } i < n\text{:} \\ &\quad \text{if } A[i] > \text{max\_so\_far}\text{:} \\ &\quad \quad \text{max\_so\_far} = A[i] \\ &\quad i = i + 1 \end{aligned}
What a Loop Invariant Is
sum=0\text{sum} = 0
i=1i = 1
while i≤n:\text{while } i \le n\text{:}
sum=sum+A[i]\text{sum} = \text{sum} + A[i]
i=i+1i = i + 1
n=5\htmlClass{lc-blue}{n = 5}
n=10\htmlClass{lc-blue}{n = 10}
??

Treating the index i\step{i} as a divider between the checked slice A[0…i−1]\workdone{A[0 \dots i - 1]} and the unchecked slice A[i…n−1]\workleft{A[i \dots n - 1]} gives the loop invariant at the snapshot point:

max_so_far\displaystyle \workdone{\text{max\_so\_far}} =max⁡(A[0…i−1])and1\displaystyle = \max(\workdone{A[0 \dots i - 1]}) \quad \text{and} \quad 1 ≤i\displaystyle \le \step{i} ≤n\displaystyle \le n

Partway through the list, max_so_far\workdone{\text{max\_so\_far}} is not yet the maximum of the whole list, but for every position of the divider i\step{i} it is the maximum of the checked slice A[0…i−1]\workdone{A[0 \dots i - 1]} to the left. When the divider reaches i=n\step{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\workdone{\text{max\_so\_far}} loop correct for any list A[0…n−1]A[0 \dots n - 1] with n≥1\given{n \ge 1} by induction across the snapshots, followed by a monovariant check that the loop terminates.

The Four-Step Correctness Proof
max_so_far=A[0]\text{max\_so\_far} = A[0]
i=1i = 1
while i<n:\text{while } i < n\text{:}
if A[i]>max_so_far:\text{if } A[i] > \text{max\_so\_far}\text{:}
max_so_far=A[i]\text{max\_so\_far} = A[i]
i=i+1i = i + 1
Invariant ?\htmlClass{lc-green}{\text{Invariant}}\ ?
max_so_far=max⁡(A[0…i−1])\htmlClass{lc-green}{\text{max\_so\_far}} = \max(\htmlClass{lc-green}{A[0 \dots i - 1]})
1≤i≤n1 \le \htmlClass{lc-pink}{i} \le n
max_so_far=31\htmlClass{lc-green}{\text{max\_so\_far} = 31}
AA
1414
88
2323
55
3131
1919
i=n\htmlClass{lc-pink}{i = n}
Text solution
Step 1: Initialization (true before the first lap)Before the loop runs, the setup sets the divider to i=1\step{i} = 1 with n≥1\given{n \ge 1}, so the slice to the left of the divider has only the single element A[0]A[0].
max_so_far\displaystyle \workdone{\text{max\_so\_far}} =A[0]\displaystyle = A[0] =max⁡(A[0…0])and1\displaystyle = \max(\workdone{A[0 \dots 0]}) \quad \text{and} \quad 1 ≤1\displaystyle \le 1 ≤n\displaystyle \le n
Step 2: Maintenance (preserved across one lap)Assuming the invariant holds at the top of a lap where i<n\given{i < n}, comparing A[i]\step{A[i]} against max_so_far\workdone{\text{max\_so\_far}} makes max_so_far\workdone{\text{max\_so\_far}} the maximum of A[0…i]A[0 \dots i] right before i\step{i} increases to inew=i+1\step{i_{\text{new}}} = \step{i} + 1.
max_so_farnew=max⁡(max_so_far,A[i])=max⁡(A[0…i])=max⁡(A[0…inew−1])and1≤inew≤n\displaystyle \begin{aligned} &\step{\text{max\_so\_far}_{\text{new}}} \\ &\quad = \max(\workdone{\text{max\_so\_far}}, \step{A[i]}) \\ &\quad = \max(A[0 \dots i]) \\ &\quad = \max(\workdone{A[0 \dots \step{i_{\text{new}}} - 1]}) \\ &\quad \text{and} \quad 1 \le \step{i_{\text{new}}} \le n \end{aligned}
Step 3: Payoff (invariant plus exit condition gives the answer)The loop exits only when i<n\given{i < n} becomes false, which combines with the invariant bound i≤n\step{i} \le n to force the divider to nn.
i≥n and 1≤i≤n  ⟹  i=n  ⟹  max_so_far=max⁡(A[0…n−1])\displaystyle \begin{aligned} &\exit{i \ge n} \text{ and } 1 \le \step{i} \le n \\ &\implies \step{i} = n \\ &\implies \workdone{\text{max\_so\_far}} \\ &\quad\quad = \goal{\max(A[0 \dots n - 1])} \end{aligned}
Step 4: Termination (a monovariant runs out)The number of unchecked elements n−i\workleft{n - i} starts at the non-negative integer n−1n - 1 and strictly decreases by 11 on every lap, so it cannot stay positive forever.
n−inew\displaystyle \workleft{n - i_{\text{new}}} =n−(i+1)\displaystyle = n - (\step{i} + 1) =(n−i)−1\displaystyle = \workleft{(n - i)} - 1 ≥0\displaystyle \ge 0

So the loop must terminate, and when it does, max_so_far\workdone{\text{max\_so\_far}} holds the maximum of the entire list A[0…n−1]A[0 \dots n - 1].

These four steps separate proving the answer is right from proving the loop stops:

Initialization+Maintenance+Payoff}Partial Correctness(right if it stops)+Termination⏟Total Correctness (stops and is right)\displaystyle \underbrace{\begin{aligned} &\left.\begin{aligned} &\text{Initialization} \\ &+ \text{Maintenance} \\ &+ \text{Payoff} \end{aligned}\right\} \begin{gathered}\scriptstyle \text{Partial Correctness} \\ \scriptstyle \text{(right if it stops)}\end{gathered} \\ &+ \text{Termination} \end{aligned}}_{\text{Total Correctness (stops and is right)}}
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\given{A \ge 0} and B≥0\given{B \ge 0}, we want to find the loop invariant for multiplying AA and BB by repeated addition:

total=0count=Bwhile count>0:total=total+Acount=count−1\displaystyle \begin{aligned} &\text{total} = 0 \\ &\text{count} = B \\ &\text{while } \text{count} > 0\text{:} \\ &\quad \text{total} = \text{total} + A \\ &\quad \text{count} = \text{count} - 1 \end{aligned}
Finding an Invariant Without a List
total=0\text{total} = 0
count=B\text{count} = B
while count>0:\text{while count} > 0\text{:}
total=total+A\text{total} = \text{total} + A
count=count−1\text{count} = \text{count} - 1
A,B≥0\htmlClass{lc-blue}{A, B \ge 0}
A=4, B=3\htmlClass{lc-blue}{A = 4,\ B = 3}
total\htmlClass{lc-green}{\text{total}}
count\htmlClass{lc-violet}{\text{count}}
Lap 0\htmlClass{lc-mute}{\text{Lap } 0}
Lap 1\htmlClass{lc-mute}{\text{Lap } 1}
Lap 2\htmlClass{lc-mute}{\text{Lap } 2}
Lap 3\htmlClass{lc-mute}{\text{Lap } 3}
Invariant\htmlClass{lc-green}{\text{Invariant}}
??

Writing out a few snapshots shows that what has already been added into total\workdone{\text{total}} and what remains to be added always add up to the full product:

total⏟work done+A⋅count⏟work left\displaystyle \underbrace{\workdone{\text{total}}}_{\workdone{\text{work done}}} + \underbrace{\workleft{A \cdot \text{count}}}_{\workleft{\text{work left}}} =A⋅B⏟whole job\displaystyle = \underbrace{A \cdot B}_{\text{whole job}}

On every lap, adding AA to total\workdone{\text{total}} and subtracting 11 from count\workleft{\text{count}} moves one AA from the work left (A⋅count\workleft{A \cdot \text{count}}) into the work done (total\workdone{\text{total}}), keeping their sum fixed at A⋅BA \cdot B until count=0\workleft{\text{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\given{A, B \ge 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\workdone{\text{total}} = \goal{A \cdot B} on exit.

Broken and Weak Invariants
total=0\text{total} = 0
count=B\text{count} = B
while count>0:\text{while count} > 0\text{:}
total=total+A\text{total} = \text{total} + A
count=count−1\text{count} = \text{count} - 1
A,B≥0\htmlClass{lc-blue}{A, B \ge 0}
??
11
Initialization\text{Initialization}
22
Maintenance\text{Maintenance}
33
Payoff\text{Payoff}

A candidate invariant can fail in two different places:

totalnew\displaystyle \step{\text{total}_{\text{new}}} =A+A\displaystyle = A + A =2A>A\displaystyle = \fails{2A > A}
Exit: count≤0Invariant: count≥0}  ⟹  count=0  ⟹  total+A⋅0=A⋅B  ⟹  total=A⋅B\displaystyle \begin{aligned} &\left.\begin{array}{r}\text{Exit: } \exit{\text{count} \le 0} \\ \text{Invariant: } \workleft{\text{count}} \ge 0\end{array}\right\} \\ &\implies \workleft{\text{count}} = 0 \\ &\implies \workdone{\text{total}} + A \cdot 0 = A \cdot B \\ &\implies \workdone{\text{total}} = \goal{A \cdot B} \end{aligned}
5

Proving Division by Repeated Subtraction

Now we can combine an accounting equation with an inequality bound in a full four-step proof. Given integers N≥0\given{N \ge 0} and d>0\given{d > 0}, we want to prove Total Correctness for finding the quotient q\workdone{q} and remainder r\workleft{r} by repeated subtraction:

r=Nq=0while r≥d:r=r−dq=q+1\displaystyle \begin{aligned} &r = N \\ &q = 0 \\ &\text{while } r \ge d\text{:} \\ &\quad r = r - d \\ &\quad q = q + 1 \end{aligned}

Specifically, we want to prove that the loop terminates with N=d⋅q+rN = \workdone{d \cdot q} + \workleft{r} and 0≤r<d0 \le \workleft{r} < d.

Proving Division by Repeated Subtraction
N≥0,  d>0\htmlClass{lc-blue}{N \ge 0},\ \ \htmlClass{lc-blue}{d > 0}
find q,r:  N=d⋅q+r,  0≤r<d\text{find } \htmlClass{lc-green}{q}, \htmlClass{lc-violet}{r}\text{:}\ \ N = \htmlClass{lc-green}{d \cdot q} + \htmlClass{lc-violet}{r},\ \ 0 \le \htmlClass{lc-violet}{r} < d
r=Nr = N
q=0q = 0
while r≥d:\text{while } r \ge d\text{:}
r=r−dr = r - d
q=q+1q = q + 1
N=14, d=4\htmlClass{lc-blue}{N = 14,\ d = 4}
q=0\htmlClass{lc-green}{q = 0}
r=14\htmlClass{lc-violet}{r = 14}
Text solution
Invariant (work done plus work left, with the remainder bound)The amount subtracted so far (d⋅q\workdone{d \cdot q}) plus the remainder left (r\workleft{r}) equals NN, and the remainder stays non-negative.
N\displaystyle N =d⋅q+randr\displaystyle = \workdone{d \cdot q} + \workleft{r} \quad \text{and} \quad \workleft{r} ≥0\displaystyle \ge 0
Step 1: Initialization (before the first lap)Setting r=N\workleft{r} = N and q=0\workdone{q} = 0 satisfies both parts of the invariant because N≥0\given{N \ge 0}.
d⋅q+r\displaystyle \workdone{d \cdot q} + \workleft{r} =d⋅0+N\displaystyle = d \cdot 0 + N =Nandr\displaystyle = N \quad \text{and} \quad \workleft{r} =N\displaystyle = N ≥0\displaystyle \ge 0
Step 2: Maintenance (across one lap when r≥d\given{r \ge d})Adding 11 to q\workdone{q} and subtracting dd from r\workleft{r} cancel out in the sum, while the loop condition r≥d\given{r \ge 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\displaystyle \begin{aligned} d \cdot \step{q_{\text{new}}} + \step{r_{\text{new}}} &= d(\workdone{q} + 1) + (\workleft{r} - d) \\ &= d \cdot q + d + r - d \\ &= \workdone{d \cdot q} + \workleft{r} = N \end{aligned}
r≥d  ⟹  rnew\displaystyle \given{r \ge d} \implies \step{r_{\text{new}}} =r−d\displaystyle = r - d ≥0\displaystyle \ge 0
Step 3: Payoff (when r≥d\given{r \ge d} becomes false)Exiting the loop means r<d\exit{r < d}, which combines with the invariant to give the complete division condition.
N\displaystyle N =d⋅q+rand0\displaystyle = \workdone{d \cdot q} + \workleft{r} \quad \text{and} \quad 0 ≤r<d\displaystyle \le \workleft{r} < d
Step 4: Termination (the remainder runs out)Because d≥1\given{d \ge 1} is a positive integer, the non-negative integer r\workleft{r} strictly decreases by at least 11 on every lap and must eventually drop below dd.
rnew\displaystyle \step{r_{\text{new}}} =r−d\displaystyle = r - d ≤r−1<r\displaystyle \le r - 1 < \workleft{r}

So the algorithm always terminates with integers q\workdone{q} and r\workleft{r} satisfying N=d⋅q+rN = \workdone{d \cdot q} + \workleft{r} and 0≤r<d0 \le \workleft{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 nn. For any real number aa and integer n≥0\given{n \ge 0}, we want to prove that this recursive function terminates and returns an\goal{a^n}:

function power(a,n):if n==0:return 1else:return a⋅power(a,n−1)\displaystyle \begin{aligned} &\text{function } \text{power}(a, n)\text{:} \\ &\quad \text{if } n == 0\text{:} \\ &\quad \quad \text{return } 1 \\ &\quad \text{else:} \\ &\quad \quad \text{return } a \cdot \text{power}(a, n - 1) \end{aligned}
Proving Recursive Algorithms by Induction
function power(a,n):\text{function } \text{power}(a, n)\text{:}
if n==0:\text{if } n == 0\text{:}
return 1\text{return } 1
else:\text{else:}
return a⋅power(a,n−1)\text{return } a \cdot \text{power}(a, n - 1)
power(a,n)=an  ?\text{power}(a, n) = \htmlClass{lc-pink}{a^n}\ \ ?
for every integer n≥0\text{for every integer } \htmlClass{lc-blue}{n \ge 0}
Text solution
Base Case (n=0\base{n = 0})When n=0\base{n = 0}, the `if n == 0` branch runs immediately without making a recursive call and returns 11.
power(a,0)\displaystyle \base{\text{power}(a, 0)} =1\displaystyle = 1 =a0\displaystyle = \goal{a^0}
Inductive Hypothesis (n=k\assume{n = k})Assume that for some integer k≥0k \ge 0, power(a,k)\assume{\text{power}(a, k)} terminates and returns aka^k.
power(a,k)\displaystyle \assume{\text{power}(a, k)} =ak\displaystyle = a^k
Inductive Step (n=k+1\step{n = k + 1})Since k+1≥1≠0k + 1 \ge 1 \ne 0, the `else` branch runs and calls power(a,k)\assume{\text{power}(a, k)}, which we replace using the inductive hypothesis.
power(a,k+1)=a⋅power(a,k)⏟ak by IH=a⋅ak=ak+1\displaystyle \begin{aligned} \step{\text{power}(a, k + 1)} &= a \cdot \underbrace{\assume{\text{power}(a, k)}}_{a^k \text{ by IH}} \\ &= a \cdot a^k = \goal{a^{k + 1}} \end{aligned}

So by mathematical induction, power(a,n)\text{power}(a, n) terminates and returns an\goal{a^n} for all integers n≥0n \ge 0.

When a recursive call shrinks the input by halving (such as ⌊n2⌋\step{\lfloor \tfrac{n}{2} \rfloor}) instead of stepping down to n−1\step{n - 1}, use strong induction and assume the function works for all smaller inputs 0≤j<n\assume{0 \le 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 nn: use ordinary induction when the recursive call steps from nn to n−1\step{n - 1} (as in power(a,n−1)\text{power}(a, \step{n - 1})), and switch to strong induction assuming 0≤j<n\assume{0 \le j < n} whenever the call jumps to a smaller input like n2\step{\tfrac{n}{2}} or n−12\step{\tfrac{n - 1}{2}}.

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]A[0 \dots n - 1]

Treat the counter i\step{i} as a divider and state that the running variable is right for the checked slice A[0…i−1]\workdone{A[0 \dots i - 1]} to the left, paired with 1≤i≤n1 \le \step{i} \le n (or 0≤i≤n0 \le \step{i} \le n if i\step{i} starts at 00), such as max_so_far=max⁡(A[0…i−1])\workdone{\text{max\_so\_far}} = \max(\workdone{A[0 \dots i - 1]}) and 1≤i≤n1 \le \step{i} \le 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\workdone{\text{total}} + \workleft{A \cdot \text{count}} = A \cdot B with count≥0\workleft{\text{count}} \ge 0, or N=d⋅q+rN = \workdone{d \cdot q} + \workleft{r} with r≥0\workleft{r} \ge 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\workleft{n - i}, count\workleft{\text{count}}, or r\workleft{r}) that starts non-negative and drops by at least 11 on every lap.

7

Practice

1

For non-negative integers x≥0\given{x \ge 0} and y≥0\given{y \ge 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\workdone{a} = \goal{x + 2y}. Four candidate loop invariants are proposed: (a) a=x+2a = x + 2 (b) a≤x+2a \le x + 2 (c) a≥xa \ge x and b≥0b \ge 0 (d) a+2b=x+2ya + 2b = x + 2y and b≥0b \ge 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\workdone{a} = \goal{x + 2y} on exit.

Test each candidate at the starting values a=xa = x and b=yb = y first, then across a general lap (not just Lap 1), and finally check whether setting b=0b = 0 forces a=x+2ya = x + 2y.

(a) Fails Step 1 (Initialization)Before the loop starts, a=x≠x+2\workdone{a} = \fails{x} \ne x + 2.
(b) Passes Step 1, but fails Step 2 (Maintenance)At the start, a=x≤x+2\workdone{a} = x \le x + 2 holds. (Watch out: checking only the first lap gives a=x+2≤x+2\workdone{a} = x + 2 \le x + 2, which makes (b) look like a valid invariant, but when y≥2\given{y \ge 2} the second lap sets a=x+4>x+2\workdone{a} = \fails{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\workdone{a} = x \ge x and b=y≥0\workleft{b} = y \ge 0, and each lap with b>0\given{b > 0} (so integer b≥1\workleft{b} \ge 1) preserves a+2≥x\step{a + 2} \ge x and b−1≥0\step{b - 1} \ge 0. However, on exit b≤0\exit{b \le 0} and b≥0\workleft{b} \ge 0 give b=0\workleft{b} = 0, leaving only a≥x\workdone{a} \ge x, which does not force a=x+2y\workdone{a} = \goal{x + 2y}.
(d) Succeeds in proving a=x+2y\workdone{a} = \goal{x + 2y} on exit
Initialization: At a=x\workdone{a} = x and b=y\workleft{b} = y, a+2b=x+2y\workdone{a} + \workleft{2b} = x + 2y and b=y≥0\workleft{b} = y \ge 0.
Maintenance: In a lap where b>0\given{b > 0} (so b≥1\workleft{b} \ge 1), (a+2)+2(b−1)=a+2b=x+2y(\step{a + 2}) + 2(\step{b - 1}) = \workdone{a} + \workleft{2b} = x + 2y and b−1≥0\step{b - 1} \ge 0.
Payoff: On exit, b≤0\exit{b \le 0} and b≥0\workleft{b} \ge 0 force b=0\workleft{b} = 0, which gives a+2(0)=x+2y\workdone{a} + 2(0) = x + 2y, so a=x+2y\workdone{a} = \goal{x + 2y}.
2

Given a list A[0…n−1]A[0 \dots n - 1] of n≥0\given{n \ge 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=0j = 0 to −1-1 is 00, write the sliding-divider loop invariant and give a four-step Total Correctness proof that the algorithm terminates with s=A[0]+A[1]\workdone{s} = \goal{A[0] + A[1]} +⋯+A[n−1]\goal{+ \dots + A[n - 1]}.

At the top of the loop, the divider sits at index ii; which indices jj have already been added into ss, and what bounds must the integer ii satisfy?

Invariants=∑j=0i−1A[j]\workdone{s} = \workdone{\sum_{j=0}^{i-1} A[j]} and 0≤i≤n0 \le \step{i} \le n (for integer i\step{i}). (Watch out: writing the upper limit as ii instead of i−1i - 1 gives s=∑j=0iA[j]\workdone{s} = \fails{\sum_{j=0}^{i} A[j]}, which fails Step 1 at i=0\step{i} = 0 because s=0\workdone{s} = 0 while ∑j=00A[j]=A[0]\fails{\sum_{j=0}^{0} A[j]} = A[0].)
Step 1 (Initialization)Before the loop, s=0\workdone{s} = 0 and i=0\step{i} = 0. The sum to the left of the divider is the empty sum ∑j=0−1A[j]=0=s\workdone{\sum_{j=0}^{-1} A[j]} = 0 = \workdone{s}, and since n≥0\given{n \ge 0}, 0≤0≤n0 \le 0 \le n holds.
Step 2 (Maintenance)Assume at the start of a lap that s=∑j=0i−1A[j]\workdone{s} = \workdone{\sum_{j=0}^{i-1} A[j]}, 0≤i≤n0 \le \step{i} \le n, and i<n\given{i < n}. After the loop body runs, snew\step{s_{\text{new}}} == s+A[i]\workdone{s} + \step{A[i]} == ∑j=0i−1A[j]+A[i]\workdone{\sum_{j=0}^{i-1} A[j]} + \step{A[i]} == ∑j=0iA[j]\sum_{j=0}^{i} A[j] and inew=i+1\step{i_{\text{new}}} = \step{i} + 1. Rewriting i\step{i} as inew−1\step{i_{\text{new}}} - 1 gives snew=∑j=0inew−1A[j]\step{s_{\text{new}}} = \workdone{\sum_{j=0}^{\step{i_{\text{new}}} - 1} A[j]}, and since ii and nn are integers with 0≤i<n0 \le \step{i} < n, 1≤inew≤n1 \le \step{i_{\text{new}}} \le n, so 0≤inew≤n0 \le \step{i_{\text{new}}} \le n.
Step 3 (Payoff)On exit, i<n\given{i < n} is false, so i≥n\exit{i \ge n}. Combined with 0≤i≤n0 \le \step{i} \le n, this forces i=n\step{i} = n, and substituting i=n\step{i} = n into the invariant gives s=∑j=0n−1A[j]\workdone{s} = \goal{\sum_{j=0}^{n-1} A[j]}.
Step 4 (Termination)The monovariant n−i\workleft{n - i} starts at n≥0n \ge 0, is an integer that strictly decreases by 11 on every lap, and cannot drop below 00 while i<n\given{i < n} holds, so the loop must terminate.
3

For a non-zero real number aa and a non-negative integer b≥0\given{b \ge 0}, consider the algorithm `p = 1; k = b; while k > 0: { p = p * a; k = k - 1 }`. State a loop invariant connecting pp and kk to aba^b, and give a four-step Total Correctness proof that the algorithm terminates with p=ab\workdone{p} = \goal{a^b}.

Because the loop multiplies by aa each lap, connect the product accumulated in pp and the kk factors of aa still left to multiply so their product equals aba^b.

Invariantp⋅ak=ab\workdone{p} \cdot \workleft{a^k} = a^b and k≥0\workleft{k} \ge 0 (for integer k\workleft{k}). (Watch out: writing an additive equation p+ak=ab\fails{p + a^k} = a^b fails Step 1 because 1+ab≠ab\fails{1 + a^b} \ne a^b, and leaving out k≥0\workleft{k} \ge 0 leaves only k≤0\exit{k \le 0} at exit instead of forcing k=0\workleft{k} = 0.)
Step 1 (Initialization)Before the loop, p=1\workdone{p} = 1 and k=b\workleft{k} = b, so p⋅ak=1⋅ab=ab\workdone{p} \cdot \workleft{a^k} = 1 \cdot a^b = a^b and k=b≥0\workleft{k} = b \ge 0.
Step 2 (Maintenance)Assume p⋅ak=ab\workdone{p} \cdot \workleft{a^k} = a^b and k≥0\workleft{k} \ge 0 at the top of the loop, and that the loop condition k>0\given{k > 0} holds (so k≥1\workleft{k} \ge 1 because kk is an integer). After one lap, pnew=p⋅a\step{p_{\text{new}}} = \workdone{p} \cdot a and knew=k−1\step{k_{\text{new}}} = \workleft{k} - 1. Then pnew⋅aknew\step{p_{\text{new}}} \cdot a^{\step{k_{\text{new}}}} == (p⋅a)⋅ak−1(\workdone{p} \cdot a) \cdot a^{\workleft{k} - 1} == p⋅ak\workdone{p} \cdot \workleft{a^k} == aba^b, and k≥1\workleft{k} \ge 1 implies knew=k−1≥0\step{k_{\text{new}}} = k - 1 \ge 0.
Step 3 (Payoff)When the loop stops, k>0\given{k > 0} is false, so k≤0\exit{k \le 0}. Combined with k≥0\workleft{k} \ge 0, this forces k=0\workleft{k} = 0, and substituting k=0\workleft{k} = 0 into p⋅ak=ab\workdone{p} \cdot \workleft{a^k} = a^b gives p⋅a0=p=ab\workdone{p} \cdot a^0 = \workdone{p} = \goal{a^b}.
Step 4 (Termination)The monovariant k\workleft{k} starts at the non-negative integer b≥0b \ge 0, stays a non-negative integer, and strictly decreases by 11 each lap, so it must reach 00 and terminate the loop.
4

For non-negative integers A≥0\given{A \ge 0} and B≥0\given{B \ge 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\workdone{\text{total}} + \workleft{x \cdot y} = A \cdot B and y≥0\workleft{y} \ge 0, prove Total Correctness that the loop terminates with total=A⋅B\workdone{\text{total}} = \goal{A \cdot B}.

In Step 2 (Maintenance), split into two cases based on whether yy is even (y=2my = 2m) or odd (y=2m+1y = 2m + 1), and write ⌊y2⌋\lfloor \tfrac{y}{2} \rfloor in terms of yy in each case.

Step 1 (Initialization)Initially total=0\workdone{\text{total}} = 0, x=Ax = A, and y=B\workleft{y} = B, so total+x⋅y=0+A⋅B=A⋅B\workdone{\text{total}} + \workleft{x \cdot y} = 0 + A \cdot B = A \cdot B and y=B≥0\workleft{y} = B \ge 0.
Step 2 (Maintenance)Assume total+x⋅y=A⋅B\workdone{\text{total}} + \workleft{x \cdot y} = A \cdot B, y≥0\workleft{y} \ge 0, and the loop condition y>0\given{y > 0} holds (so integer y≥1\workleft{y} \ge 1).
Case 1 (y\workleft{y} is even): y=2m\workleft{y} = 2m for an integer m≥1m \ge 1, so ⌊y2⌋=m=y2\lfloor \tfrac{y}{2} \rfloor = m = \tfrac{y}{2}. The `if` branch does not run, giving totalnew=total\step{\text{total}_{\text{new}}} = \workdone{\text{total}}, xnew=2x\step{x_{\text{new}}} = 2x, and ynew=y2\step{y_{\text{new}}} = \tfrac{y}{2}. Then totalnew+xnew⋅ynew\step{\text{total}_{\text{new}}} + \step{x_{\text{new}}} \cdot \step{y_{\text{new}}} == total+(2x)(y2)\workdone{\text{total}} + (2x)(\tfrac{y}{2}) == total+x⋅y\workdone{\text{total}} + \workleft{x \cdot y} == A⋅BA \cdot B and ynew=m≥0\step{y_{\text{new}}} = m \ge 0.
Case 2 (y\workleft{y} is odd): y=2m+1\workleft{y} = 2m + 1 for an integer m≥0m \ge 0, so ⌊y2⌋=m=y−12\lfloor \tfrac{y}{2} \rfloor = m = \tfrac{y - 1}{2}. (Watch out: writing ynew=y2\step{y_{\text{new}}} = \fails{\tfrac{y}{2}} instead of y−12\tfrac{y - 1}{2} when y\workleft{y} is odd gives (total+x)+(2x)(y2)=A⋅B+x(\text{total} + x) + (2x)(\tfrac{y}{2}) = A \cdot B \fails{+ x}, making the invariant appear to fail by +x\fails{+x}.) The `if` branch runs, giving totalnew=total+x\step{\text{total}_{\text{new}}} = \workdone{\text{total}} + x, xnew=2x\step{x_{\text{new}}} = 2x, and ynew=y−12\step{y_{\text{new}}} = \tfrac{y - 1}{2}. Then totalnew+xnew⋅ynew\step{\text{total}_{\text{new}}} + \step{x_{\text{new}}} \cdot \step{y_{\text{new}}} == (total+x)+(2x)y−12(\workdone{\text{total}} + x) + (2x)\tfrac{y - 1}{2} == total+x+x(y−1)\text{total} + x + x(y - 1) == total+x⋅y\workdone{\text{total}} + \workleft{x \cdot y} == A⋅BA \cdot B and ynew=m≥0\step{y_{\text{new}}} = m \ge 0.
Step 3 (Payoff)On exit, y≤0\exit{y \le 0} and y≥0\workleft{y} \ge 0 force y=0\workleft{y} = 0, so total+x⋅0=A⋅B\workdone{\text{total}} + x \cdot 0 = A \cdot B, giving total=A⋅B\workdone{\text{total}} = \goal{A \cdot B}.
Step 4 (Termination)The monovariant y\workleft{y} starts at B≥0B \ge 0 and remains a non-negative integer; on every lap y≥1\workleft{y} \ge 1, so ynew=⌊y2⌋≤y2<y\step{y_{\text{new}}} = \lfloor \tfrac{y}{2} \rfloor \le \tfrac{y}{2} < \workleft{y}, meaning y\workleft{y} strictly decreases by at least 11 each lap and must reach 00.
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\given{n \ge 0}, `sq(n)` terminates and returns n2\goal{n^2}.

In the inductive step for n=k+1n = k + 1, substitute k+1k + 1 for every nn in the `else` branch before applying the inductive hypothesis to `sq(k)`.

Base Case (n=0\base{n = 0})When n=0\base{n = 0}, the condition `n == 0` is true, so `sq(0)` immediately terminates and returns 0=020 = \goal{0^2}.
Inductive HypothesisSuppose that for some integer k≥0k \ge 0, `sq(k)` terminates and returns k2k^2.
Inductive Step (n=k+1\step{n = k + 1})Since k≥0k \ge 0, k+1≥1≠0k + 1 \ge 1 \ne 0, so `sq(k + 1)` takes the `else` branch and evaluates sq((k+1)−1)+2(k+1)−1\assume{\text{sq}((k + 1) - 1)} + 2(k + 1) - 1 == sq(k)+2k+1\assume{\text{sq}(k)} + 2k + 1. (Watch out: forgetting to plug k+1k + 1 into 2n−12n - 1 leaves sq(k)+2k−1=k2+2k−1\assume{\text{sq}(k)} + \fails{2k - 1} = k^2 + \fails{2k - 1} instead of (k+1)2\goal{(k + 1)^2}.) By the inductive hypothesis, `sq(k)` terminates and returns k2k^2. Substituting k2k^2 for `sq(k)`, `sq(k + 1)` terminates and returns k2+2k+1=(k+1)2k^2 + 2k + 1 = \goal{(k + 1)^2}. By induction, `sq(n)` terminates and returns n2\goal{n^2} for all integers n≥0n \ge 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 aa and all integers n≥0\given{n \ge 0}, `mult(a, n)` terminates and returns a⋅n\goal{a \cdot n}.

For n=k≥1n = k \ge 1, assume the claim holds for all integers jj with 0≤j<k0 \le 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\base{n = 0})When n=0\base{n = 0}, `n == 0` is true, so `mult(a, 0)` immediately terminates and returns 0=a⋅00 = \goal{a \cdot 0}.
Strong Inductive HypothesisLet k≥1k \ge 1 be an integer and assume that for every integer jj with 0≤j<k\assume{0 \le j < k}, `mult(a, j)` terminates and returns a⋅ja \cdot j. (Watch out: assuming the claim only for k−1\fails{k - 1} cannot handle the recursive calls at k2\step{\tfrac{k}{2}} or k−12\step{\tfrac{k - 1}{2}}, and in each branch you must verify that the recursive argument is an integer satisfying 0≤j<k\assume{0 \le j < k}.)
Inductive Step (n=k\step{n = k})Since k≥1≠0k \ge 1 \ne 0, the base-case branch does not run.
Case 1 (kk is even): The second branch calls `mult(a, k / 2)`. Since k≥2k \ge 2 is an even integer, k2\step{\tfrac{k}{2}} is an integer with 0≤k2<k0 \le \step{\tfrac{k}{2}} < k. By the strong inductive hypothesis, `mult(a, k / 2)` terminates and returns a⋅k2a \cdot \tfrac{k}{2}, so `mult(a, k)` terminates and returns 2⋅(a⋅k2)=a⋅k2 \cdot (a \cdot \tfrac{k}{2}) = \goal{a \cdot k}.
Case 2 (kk is odd): The `else` branch calls `mult(a, (k - 1) / 2)`. Since k≥1k \ge 1 is an odd integer, k−12\step{\tfrac{k - 1}{2}} is an integer with 0≤k−12<k0 \le \step{\tfrac{k - 1}{2}} < k. By the strong inductive hypothesis, `mult(a, (k - 1) / 2)` terminates and returns a⋅k−12a \cdot \tfrac{k - 1}{2}, so `mult(a, k)` terminates and returns a+2⋅(a⋅k−12)=a+a(k−1)=a⋅ka + 2 \cdot (a \cdot \tfrac{k - 1}{2}) = a + a(k - 1) = \goal{a \cdot k}.
By strong induction, `mult(a, n)` terminates and returns a⋅n\goal{a \cdot n} for all integers n≥0n \ge 0.