-
Notifications
You must be signed in to change notification settings - Fork 4
/
ex1-17-mul-by-fast-add.scm
40 lines (35 loc) · 1.28 KB
/
ex1-17-mul-by-fast-add.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
; Ex. 1.17 "Fast-multiplication"
; This procedure to multiply, using only addition, grows by
; theta(log n) steps and in theta(log n) space owing to
; deferred operations.
; (define (* a b)
; ; I displaying object '*' ONLY as a quick-n-dirty way to visually
; ; verify order of growth.
; (display *)
; (display " ")
; (cond ((= b 0) 0)
; ((halve b) (double (* a (halve b))))
; (else (+ a (double (* a (halve (- b 1))))))))
(define (* a b)
; I display object '*' ONLY as a quick-n-dirty way to visually
; verify order of growth.
(display *)
(display " ")
(cond ((= b 0) 0)
((= b 1) a)
((halve b) (* (double a) (halve b)))
(else (+ a (* a (- b 1))))))
; (halve) as a black-box abstraction
; Strictly speaking, one can argue that division and remainder
; are illegal primitives based on the wording of the question.
; However, since I use halve as a black-box abstraction,
; I take the liberty to assume that its internal definition
; can be easily substituted by one of the well-understood
; division algorithm that operate using only primitive addition
; and subtraction.
(define (halve x)
(if (= (remainder x 2) 0)
(/ x 2)
#f))
; double in terms of primitive addition
(define (double x) (+ x x))