2

I'm trying to find a loop invariant so that we can prove this program partially-correct:

{ n >= 1 } pre-condition 
i = 1;
z = 1;
while (i != n) {
  i = i + 1;
  z = z + i*i;
}
{ z = n*(n+1)*(2*n + 1)/6 } post-condition

I am really stuck. Some of the invariants I've tried so far are:

z <= n*(n+1)*(2*n + 1)/6 ^ i <= n

and

z = i*(i+1)*(2*i + 1)/6 ^ i <= n

I would really appreciate some advice.

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
user27587
  • 21
  • 2
  • Could it be that there is a typo in your post-condition? `... = 6` seems odd (since it says that `z` is always equal to the fixed number `6`). – chris Jul 29 '13 at 03:24
  • Btw: Does the symbol `^` in your post stand for "exponentiation" (as it does in my answer) or did you try to approximate the symbol for logical "and" (which I would rather write as `&&` or `/\ `). I'm just asking because `z = ... && i <= n` would make more sense than the alternative interpretation. – chris Jul 29 '13 at 04:32

1 Answers1

0

To find an appropriate invariant you have to have an intuition what the investigated function actually does. In your example the value i^2 is successively added to the accumulator z. So the function computes (just going through the first few iterations of the while-loop by hand and then generalizing):

1^2 + 2^2 + 3^2 + 4^2 + 5^2 + ... + n^2

or written a bit more formally

SUM_{i=1}^{n} i^2

i.e., the sum of all squares of i ranging from 1 to n.

On first sight this might not look similar to your post-condition. However, it can be shown by induction on n that the above sum is equal to

(n*(n+1)*(2*n + 1))/6

which I guess is the intended post-condition. Since we now know that the post-condition is equal to this sum, it should be easy to read off the invariant from the sum.

chris
  • 4,988
  • 20
  • 36