SICP-2nd-Edition-Exercise-1.16

From Boozled

Jump to: navigation, search

Contents

Exercise 1.16 From SICP

Details from SICP are here

Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that

\left(b^\left(n/2\right)\right)^2 = \left(b^2\right)^\left(n/2\right)

, keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product a * bn is unchanged from state to state. At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.)


Attempt

If our state variable starts with a = 1 then our first iteration has:

1 * bn = a * bn = bn

So bn must be maintained through the procedure.

The clue they give us is

\left(b^\left(n/2\right)\right)^2 = \left(b^2\right)^\left(n/2\right) = b^n

The method used by the authors is that when they halved n they would then square the result returned from (fast-iter). Our method will square b then halve n and pass this to (my-fast-iter).

Scheme

  1. (define (fast-expt b n)
  2.   (cond ((= n 0) 1)
  3.         ((even? n) (square (fast-expt b (/ n 2))))
  4.         (else (* b (fast-expt b (- n 1))))))
  5. ; I use the "fast-expt" from the book to display a*b^n as the procedure is run
  6. (define (square x) (* x x))
  7. (define (my-fast-expt a b n)  
  8.   (cond ((= n 0) 
  9.          a)
  10.         ((even? n) 
  11.          (display (* a (fast-expt b n))) (newline) 
  12.          (my-fast-expt a (square b) (/ n 2)) )
  13.         (else      
  14.          (display (* a (fast-expt b n))) (newline) 
  15.          (my-fast-expt (* a b) b (- n 1)))))
  16.  
  17. (define base  3)
  18. (define power 2)
  19. (define state 1)
  20. (display (my-fast-expt state base power))

Parent Course

6.001_Structure_and_Interpretation_of_Computer_Programs

Further Reading

Personal tools