Section 3.5
- 4. There are three cases. If x < y initially, then min is set
equal to x, so (x <= y ^ min = x) is true. If x = y initially, then
min is set equal to y (which equals x), so again (x <= y ^ min = x) is
true. Finally, if x > y initially, then min is set equal to y, so (x >
y ^ min = y) is true. Hence in all cases the disjunction (x <= y ^ min
= x) V (x > y ^ min = y) is true.
- 6. There are three cases. If x < 0, then y is set equal to
-2|x|/x = (-2)(-x)/x = 2. If x > 0, then y is set equal to 2|x|/x =
2x/x = 2. If x = 0, then y is set equal to 2. Hence in all cases y =
2 at the termination of this program.
- 8. In Section 3.4, Algorithm 8 was proven correct. It is clearly
correct if n = 0 or n = 1, so we assume that n >= 2. Then the program
terminates when the for loop terminates, so we concentrate our
attention on that loop. Before the loop begins, we have x = 0 and y =
1. Let the loop invariant p be (x = fi-1 ^ y = fi) V (i is undefined ^
x = f0 ^ y = f1). This is true at the beginning of the loop, since i
is undefined and f0 = 0 and f1 = 1. What we must show now is p ^ (1
<= i < n){S}p. If p ^ (1 <= i < n), then x = fi-1 and y = fi. Hence
z becomes fi+1 by the definition of the Fibonacci sequence. Now x
becomes y, namely fi, and y becomes z, namely fi+1, and i is
incremented. Hence for this new (defined) i, x = fi-1 and y = fi, as
desired. We therefore conclude that upon termination x = fi-1 ^ y =
fi ^ i = n; hence y = fn as desired.
- 12. Suppose that the initial assertion is true before the proram
begins, so that a and d are positive integers. Consider the following
loop invariant p: "a = dq + r and r >= 0." This is true before the
loop starts, since the equation then states a = d(0) + a, and we are
told that a (which equals r at this point) is a positive integer, hece
greater than or equal to 0. Now we must show that if p is true and r
>= d before some pass through the loop, then it remains true after the
pass. Certainly we still have r >= 0, since all that happended to r
was the subtraction of d, and r >= d to begin this pass.
Let q' denote the new value of q and r' the new value of r. Then dq'
+ r' = d(q+1) + (r-d) = dq + d + r - d = dq + r = a, as desired.
Furthermore, the loop terminates eventually, since one cannot
repeatedly subtract the positive integer d from the positive integer r
without r eventually becoming less than d. When the loop terminates,
the loop invariant p must still be true, and the condition r >= d must
be false, i.e., r