|
Program Correctness
An Introduction |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
Given a while loop with guard \(G\), pre-conditions, post-conditions, and a predicate \(I(k)\) describing the loop invariant at iteration \(k\), the loop is correct if the following hold:
Basis Property:
Inductive Property:
Suppose that before iteration \(k\) of the loop the guard is true (i.e., \(k \lt m\) is true) and \(I(k)\) is true (i.e., \(k = n\) is true and \(p = n x\) is true).
We must show that after the iteration, \(I(k+1)\) is true.
Eventual Falsity of the Guard:
Correctness of the Post Condition:
unsigned int floorsqrt(unsigned long x)
{
unsigned long r, nr, m;
r = 0;
m = 0x40000000;
do
{
nr = r + m;
if (nr <= x)
{
x -= nr;
r = nr + m;
}
r >>= 1;
m >>= 2;
} while (m != 0);
return(r);
}
Basis Property:
Inductive Property:
Suppose that before iteration \(k\) of the loop the guard is true (i.e., \(b_k \gt 0\) is true) and \(I(k)\) is true [i.e., \(\gcd(a_k , b_k) = \gcd(a_0 , b_0)\) is true and \(b_k \geq 0\) is true and \(a_k \gt b_k\) is true].
We must show that after the iteration, \(I(k+1)\) is true (i.e., \(\gcd(a_{k+1},b_{k+1}) = \gcd(a_0 , b_0)\) is true and \(b_{k+1} \geq 0\) is true and \(a_{k+1} \gt b_{k+1}\) is true).
Eventual Falsity of the Guard:
Correctness of the Post Condition: