Skip to content

Loop Invariants

What's the next number \(f(5)\), and what's the formula (recursive and general formula) for \(f(n)\) for some arbitrary \(n\)?

\[ f(1) = 1, \quad f(2) = 3, \quad f(3) = 5, \quad f(4) = 7, \quad f(5) = \ ? \]
Are you sure the answer is 9?

It's 217341, obviously.

\[ f(x) = \frac{18111}{2}x^4 - 90555x^3 + \frac{633885}{2}x^2 - 452773x + 217331 \]

This gives \(f(1) = 1\), \(f(2) = 3\), \(f(3) = 5\), \(f(4) = 7\) and \(f(5) = 217341\).

Ok, the answer is 9.

  • Recursive form: \(f(x) = f(x - 1) + 2\) with \(f(1) = 1\)
  • General form: \(f(x) = 2x - 1\)

Consider this code, how does i relate to v?

int v = 1;
int i = 1;
// v == 2i - 1 == f(i)
while (i <= 5) {
    // v == 2i - 1 == f(i)
    v += 2;
    i++;
    // v == 2i - 1 == f(i)
}

The loop body is the recursive form, since every iteration does v += 2.

Compare it with the recursive version.

// f_rec(x) == 2x - 1
int f_rec(int x) {
    if (x == 1) return 1;
    return f_rec(x - 1) + 2;
}

int f_loop(int x) {
    int v = 1;
    int i = 1;
    // v == 2i - 1
    while (i < x) {
        // v == 2i - 1
        v += 2;
        i++;
        // v == 2i - 1
    }
    // v == 2i - 1
    return v;
}

The difference between iteration and recursion is when the meaning shows up. With recursion, the meaning comes first. You have to decide what f(x) means before you can trust f(x - 1), which is the first step in how to recursion. With a loop, the meaning comes last. You write the code first, and only afterwards ask what the loop invariant is.

A loop invariant is the general formula for a loop. What it buys you is the ability to teleport to any iteration.

Mathematical Formality: What's a loop invariant?

A loop invariant is an assertion that needs to be true at three places.

  1. Before the loop
  2. At the start of every iteration
  3. At the end of every iteration

In f_loop, those are the // v == 2i - 1 above the while and the two inside the body. The one after the loop comes for free, since the loop can only exit right after place 1 or place 3.

For the PL enthusiast, see inductive invariants.