SICP Exercise 1.18
問題文
Using the results of exercises 1.16 and 1.17, devise a procedure that generates an iterative process for multiplying two integers in terms of adding, doubling, and halving and uses a logarithmic number of steps.
解答案
まだすぐ反復的プロセスを書けるほどには慣れていない...けど、こういう感じだよね。
(define (even? n)
(= (remainder n 2) 0))
(define (double x)
(+ x x))
(define (halve x)
(/ x 2))
(define (*-iter a b n)
(cond ((= b 0) n)
((even? b) (*-iter (double a) (halve b) n))
(else (*-iter a (- b 1) (+ a n)))))
(define (* a b)
(*-iter a b 0))