Before you tackle the homework, remind yourself of our general hw policies.
(The 4ed. page-numberings will be added mar.01(sat) eve.
xn:
;; pow: real, natnum --> real
;; Return xn.
;;
(define (pow x n)
(cond [(zero? n) 1]
[(even? n) (sqr (pow x (quotient n 2)))]
[(odd? n) (* x (sqr (pow x (quotient n 2))))]
Be sure to clearly state which proof method you are using.
sqr is a function which squares its input.
You may take as given, that (quotient n 2) returns
n/2 if
n even,
and
(n-1)/2 if
n odd.
The above procedure is called "repeated squaring", and is based on the fact that to compute (for example) 504^18, you don't need to do 18 multiplications, but rather just compute (504^9)^2. In turn, 504^9 can be computed by observing 504^9 = 504^8*504 = (504^4)^2*504.
// pow: compute xn.
//
rational pow( rational x, natnum n) {
rational soFar <-- 1
natnum restOfN <-- n
rational xToTwoToI <-- x // This will be x^(2^i), where i is number of times through loop.
// LoopInvariant: x^n = (xToTwoToI ^ restOfN) * soFar.
while (restOfN > 0) {
if odd?(restOfN) soFar <-- soFar * xToTwoToI
restOfN <-- quotient(restOfN, 2)
xToTwoToI <-- xToTwoToI * xToTwoToI // Repeatedly square.
}
return soFar
}
Using the loop invariant as stated in the code,
show the four parts of the proof obligation for the loop.
(You can assume that your programming language is sane, and that rationals and natnums are represented exactly without round-off or overflow error.)