Thursday, August 22, 2019

SICP in Clojure: Chapter 1, Exercise 18

This is my Clojure solution to Chapter 1, Exercise 18:

(ns sicp.ch1.ex18
  (:require [sicp.ch1.ex17 :as sicp-ch1-ex17]))

(defn fast-multiply-iter
  ([b n]
   (fast-multiply-iter 0 b n))
  ([a b n]
   (cond (zero? n) a
         (even? n) (fast-multiply-iter a (sicp-ch1-ex17/double-it b)
                                       (sicp-ch1-ex17/halve-it n))
         :else (fast-multiply-iter (+ a b) b (dec n)))))

(fast-multiply-iter 2 8) ; => 16

(fast-multiply-iter 2 9) ; => 18

(every? #(= (sicp-ch1-ex17/fast-multiply 2 %)
            (fast-multiply-iter 2 %))
        (range 10)) ; => true

No comments: