]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_17.clj
Solution to 4.33. This had been difficult to get right, though conceptually it was
[sicp.git] / src / sicp / ex1_17.clj
1 (ns sicp.ex1_17
2   (:use [sicp utils]
3         [clojure.contrib trace test-is]))
4
5 ;; exercise 1.17:
6 (defn mult [a b]
7   (if (= b 0)
8     0
9     (+ a (mult a (- b 1)))))
10
11 ;; double
12 ;; product = 2 * (a * (b/2)) for even b
13 ;;         = a    + (a * (b - 1)) for odd b
14 (defn fast-mult [a b]
15   (cond (= b 0) 0
16         (= b 1) a
17         (even? b) (twice (fast-mult a (half b)))
18         :else (+ a (fast-mult a (- b 1)))))