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?
For $a,b > 1$, we know that $a,b < ab$. Your algorithm adds positive number to either $x$ or $y$, in each step. That means that in each step exactly one of this values grows, so - at one point - you'll get one of these:
- $x \ge ab$, $y < ab$; or
- $x < ab$, $y \ge ab$; or
- $x = y$.
Since you worry about $\le ab$, let us assume 1: $x \ge ab$, $y < ab$. Notice that $x = ab$. If this wasn't the case, we'd have $x - b \ge ab$, so the last step wouldn't enlarge $x$ and its value wouldn't get $>ab$, which is a contradiction.
So, $x = ab$, $y < ab = x$.
As long as $y < x$, the algorithm will keep on adding $b$ to $y$. So, your $y$ will be getting values $y_0, y_0 + b, \dots, y_0 + kb$ for some $k \in \mathbb{N}$ ($y_0$ denotes the value that $y$ had when $x$ reached $ab$).
Now, same as with $x$: if $y_0 + kb > ab$, then $y_0 + (k-1)b \ge ab$, because there are no numbers between $y_0 + (k-1)b$ and $y_0 + kb$ that are divisible by $b$. But, we know that $(k-1)b < ab$, so this is a contradiction. Hence, $y_0 + kb = ab = x$ and the algorithm ends.
The same goes for case 2, and the case 3 says only that the algorithm may finish sooner.
You still need to show that the value that the algorithm computes is the least (common multiplier). This can be done by repeating what I did above, but using $m = \operatorname{lcm}(a,b)$ instead of $ab$, thus showing that $x$ and $y$ cannot grow beyond it.
Best Answer
I'd use
x == max(A[0..i-1])
as the loop invariant, positioned immediately after the increment toi
(last line ofwhile
loop). To make it even easier to prove that the invariant holds on each pass through the loop, you can use more assertions within the loop body:It's then obviously true that once the loop has terminated,
x == max(A[0..n-1])
.