[Math] Tips for constructing basic loop invariants

algorithms

One of the topics that I've struggled to grasp the most in my basic computer theory course is that of making a loop invariant to prove correctness of an algorithm. Even with what should be fairly straightforward algorithms, I just don't really understand what sort of properties I should be using in order to make an effective loop invariant that helps to prove algorithm correctness.

Here's an example of some basic pseudocode that I can't create a loop invariant for:

FUNCTION(a, b):
p <- 1
l <- 0
while p < a:
    p <- p * b
    l <- l + 1
return l

Does anyone have some tips or resources that would help me get a better grasp on making loop invariants?

Best Answer

For that example, you want an invariant about $p$ and $l$ because these are the values that are changing. Before the loop, you have $p=1$ when $l=0$. After the first time trhough the loop, you have $p=b$ and $l=1$. Then $p=b^2$ when $l=2$. Now you can guess a general invariant: $p=b^l$. Next, prove it by induction. So, what is the value of $p$ (and $l$) when the loop ends? For that you need to answer: how many times is the loop executed?

Related Question