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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (define (double x) (+ x x)) | |
| (define (halve x) (/ x 2)) | |
| (define (odd? n) | |
| (= | |
| (remainder n 2) | |
| 1)) | |
| (define (even? n) | |
| (= | |
| (remainder n 2) | |
| 0)) | |
| (define (fast-mult-it b n) | |
| (fast-mult-iter 0 b n)) | |
| (define (fast-mult-iter a b n) | |
| (cond | |
| ((= n 0) a) | |
| ((even? n) | |
| (fast-mult-iter | |
| a | |
| (double b) | |
| (halve n))) | |
| ((odd? n) | |
| (fast-mult-iter | |
| (+ a b) | |
| b | |
| (- n 1))))) | |