Solution to SICP Exercise 1.18

Structure and Interpretation of Computer Programs

Solution to Exercise 1.18:

(define (double x)
(+ x x))

(define (halve x)
(/ x 2))

(define (even? n)
(= (remainder n 2) 0))

(define (it-fast-mult a b)
(iter 0 a b))

(define (iter total a b)
(cond ((or (= a 0) (= b 0)) 0)
((= b 1) (+ total a))
((even? b) (iter total (double a) (halve b)))
(else (iter (+ total a) a (- b 1)))))

Advertisements