1.17

Exercise 1.17: The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is assumed that our language can only add, not multiply) is analogous to the expt procedure:

(define (* a b)
  (if (= b 0)
      0
      (+ a (* a (- b 1)))))

This algorithm takes a number of steps that is linear in b. Now suppose we include, together with addition, operations double, which doubles an integer, and halve, which divides an (even) integer by 2. Using these, design a multiplication procedure analogous to fast-expt that uses a logarithmic number of steps.

Assume b is even first:

(define (double a) (* a 2))
(double 2)
(define (halve b) (/ b 2))
(halve 4)
(define (fast-multi a b)
    (if (= b 1) 
        a 
        (double (fast-multi a (halve b)))
)
)

(fast-multi 3 4)

The process is recursive:

(fast-multi 3 4) -----------------------------\
(double (fast-multi 3 2))                     |
(double (double (fast-multi 3 1)))            |
(double (double 3))                           |
(double 6)                                    |
12               <----------------------------/

For b is not even, we subtract 1 from it:

(define (fast-multi-all a b) (if (= 0 (mod b 2)) (fast-multi a b) (+ a (fast-multi a (- b 1)))))
(fast-multi-all 3 5)

results matching ""

    No results matching ""