Skip to content

Commit

Permalink
Exercise 1.18 (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
SmetDenis authored Oct 15, 2023
1 parent 7d21556 commit c11c6c6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/sicp/chapter_1/ex_1_18.clj
Original file line number Diff line number Diff line change
@@ -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))
6 changes: 6 additions & 0 deletions test/sicp/chapter_1/ex_1_18_test.clj
Original file line number Diff line number Diff line change
@@ -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))))

0 comments on commit c11c6c6

Please sign in to comment.