SICP 1.2 exercises cont. 6

1.16

(define (fast-expt-2 b n)
  (fast-expt-iter 1 b n))

(define (fast-expt-iter a b n)
  (cond (( = n 0) a)
        ((even? n) (fast-expt-iter (square a) b (/ n 2)))
        (else (fast-expt-iter (* a b) b (- n 1)))))

Comments: I actually did this quite quickly, although it did take a little bit of trial and error. The idea of an invariant quantity is pretty interesting.



Leave a comment