Blob


1 ;; 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.40
3 ;; invariant quantity
4 ;; t + a * b = {
5 ;; t if b = 0
6 ;; t + 2 * a * (b/2) if b even
7 ;; (t+a) + a * (b-1) if b odd
8 ;; }
10 (define (fast-mult-iter a b t)
11 (cond ((= b 0) t)
12 ((even? b) (double fast-mult-iter a (halve b) t))
13 (else (fast-mult-iter a (- b 1) (+ t a)))))
15 (define (test-case actual expected)
16 (load-option 'format)
17 (newline)
18 (format #t "Actual: ~A Expected: ~A" actual expected))
19 (test-case (fast-mult 0 0) 0)
20 (test-case (fast-mult 0 1) 0)
21 (test-case (fast-mult 0 8) 0)
22 (test-case (fast-mult 5 0) 0)
23 (test-case (fast-mult 2 1) 2)
24 (test-case (fast-mult 3 3) 9)
25 (test-case (fast-mult 5 4) 20)
26 (test-case (fast-mult 12 13) 156)
27 (test-case (fast-mult 12 24) 288)