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.

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s