2015-04-22
This exercise requires the design of a procedure that evolves an
iterative exponentiation process using successive squaring. It should
use constant space and a logarithmic number of steps. The hint is to
note that a
is another state variable along with the base
b
and exponent n
. Here is the
implementation:
(define (even? x)
(= (remainder x 2) 0))
(define (expt b n)
(expt-iter 1 b n))
(define (expt-iter a b n)
(cond ((= n 0) a)
((even? n) (expt-iter a (square b) (/ n 2)))
(else (expt-iter (* a b) b (- n 1)))))
Here, expt-iter
starts with the state variables
a = 1
, b
, the base, and n
, the
exponent.
We will the use the notation a
, b
and
n
, respectively.
When the exponent n
falls to zero, our invariant says
that a
. The correctness of this can be readily
verified for expr-iter
with
arguments cond
in expt-iter
preserves the
invariant through the next recursive call to itself.
For even values of
For odd values of
Maintaining an invariant across state transformations is a powerful way of designing iterative processes, and also makes it easy to reason for the correctness of the procedures behind such processes.