// Set x to the sum of the primes in 2..n-1
x= 0;
// invariant inv: x is sum of primes in 2..k-1
for (int k= 2; k <= n; k= k+1) {
if (k is a prime)
x= x + k;
}
// post: x is sum of primes in 2.. n-1 |
A: initialization doesn’t make inv true
B: Postcondition not true at end
C: Not always progress toward termination
D: Repetend doesn’t keep inv true
E: All 4 loopy questions satisfied
The answer is B. The loop terminates with k = n+1, and with k = n+1, the invariant indicates that
x is the sum of primes in 2..n.
The loop condition should be k < n . |