From c11c6c690e2276460437c4dc8ad7eba8a4cac13e Mon Sep 17 00:00:00 2001 From: Denis Smetannikov Date: Sun, 15 Oct 2023 23:24:08 +0300 Subject: [PATCH] Exercise 1.18 (#13) --- src/sicp/chapter_1/ex_1_18.clj | 22 ++++++++++++++++++++++ test/sicp/chapter_1/ex_1_18_test.clj | 6 ++++++ 2 files changed, 28 insertions(+) create mode 100644 src/sicp/chapter_1/ex_1_18.clj create mode 100644 test/sicp/chapter_1/ex_1_18_test.clj diff --git a/src/sicp/chapter_1/ex_1_18.clj b/src/sicp/chapter_1/ex_1_18.clj new file mode 100644 index 0000000..d255a4b --- /dev/null +++ b/src/sicp/chapter_1/ex_1_18.clj @@ -0,0 +1,22 @@ +(ns sicp.chapter-1.ex-1-18 + (:require [sicp.chapter-1.ex-1-16 :refer [expt]])) + +; Exercise 1.18 +; Using the results of Exercise 1.16 and Exercise 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. + +(defn fast-mult-v2 + [a b product counter] + (cond (= a 0) product + (= (mod a 2) 1) (fast-mult-v2 (/ a 2) + b + (+ product (* (expt 2 counter) b)) + (+ counter 1)) + :else (fast-mult-v2 (/ a 2) + b + product + (+ counter 1)))) + +(defn mult + [a b] + (fast-mult-v2 a b 0 0)) diff --git a/test/sicp/chapter_1/ex_1_18_test.clj b/test/sicp/chapter_1/ex_1_18_test.clj new file mode 100644 index 0000000..68772df --- /dev/null +++ b/test/sicp/chapter_1/ex_1_18_test.clj @@ -0,0 +1,6 @@ +(ns sicp.chapter-1.ex-1-18-test + (:require [clojure.test :refer :all]) + (:require [sicp.chapter-1.ex-1-18 :refer [mult]])) + +(deftest mult-test + (is (= 0 (mult 0 19))))