8C. Loop invariants

Look at the pre-simulation for power from the preceding page, with x = 3 and n = 4.

     p    k    n
     3    1    4
     9    2
    27    3
    81    4

  1. In the first line, p = 3 and k = 1. Notice that, for those values of p and k, p = xk, since 3 = 31.

  2. In the second line, p = 9 and k = 2. Notice that, for the values in the second line, p = xk since 9 = 32.

In fact, at every line, p = xk. We say that assertion p = xk is a loop invariant of this loop.

A loop invariant is an assertion about the current values of the variables that is true whenever the program is at the beginning of the loop. It cannot talk about prior values of the variables or what their values will be in the future. It only mentions the current values of the variables.

What is the point of a loop invariant? If the loop invariant is true at every line of the hand simulation, then it must be true for the last line. But in the last line, we know that k = n. (If that were false, the loop would keep going.) Putting together the two facts

p = xk
k = n

that are both true for the last line, we get that p = xn. That gives a bare-bones proof that our algorithm is correct, and increases our confidence in our function definition.


A loop invariant for the gcd function

Let's look at the gcd from the previous page. Here is a hand simulation of gcd(15, 40) (so x = 15 and y = 40, and they don't change during the loop).

      m     n     x     y
     15    40    15    40
     40    15
     15    10
     10     5
      5     0

Can you find an interesting loop invariant for the loop in the gcd function? Remember that it must only concern the current values of the variables. It can talk about the current values of all of the variables, x, y, m and n.

A useful invariant for the gcd loop is

gcd(m, n) = gcd(x, y)

That holds for every line of the hand simulation. So it must hold for the last line, where n = 0. So, in the last line,

gcd(m, 0) = gcd(x, y)

Since Euclid tells us that gcd(m, 0) = m, it is clear that m is the correct result.