Skip to content

Commit

Permalink
Exercise 1.17
Browse files Browse the repository at this point in the history
  • Loading branch information
Denis Smet committed Oct 15, 2023
1 parent ca08c3b commit b5edaa7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/sicp/chapter_1/ex_1_17.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
(ns sicp.chapter-1.ex-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:
;

(defn multi
[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.

(defn multi-fast
[a b]
(cond (= b 0) 0
(even? b) (* 2 (multi-fast a (/ b 2)))
:else (+ a (multi-fast a (- b 1)))))
17 changes: 17 additions & 0 deletions test/sicp/chapter_1/ex_1_17_test.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
(ns sicp.chapter-1.ex-1-17-test
(:require [clojure.test :refer :all]
[sicp.chapter-1.ex-1-17 :refer [multi multi-fast]]))

(deftest multi-test
(time (is (= 2 (multi 1 2)))) ; "Elapsed time: 2.383128 msecs"
(time (is (= 50 (multi 10 5)))) ; "Elapsed time: 1.087389 msecs"
(time (is (= 6703582689499996764
(multi 12345340404 543005091)))) ; "Elapsed time: 0.852849 msecs"
)

(deftest multi-fast-test
(time (is (= 2 (multi-fast 1 2)))) ; "Elapsed time: 1.258788 msecs"
(time (is (= 50 (multi-fast 10 5)))) ; "Elapsed time: 1.582771 msecs"
(time (is (= 6703582689499996764
(multi-fast 12345340404 543005091)))) ; "Elapsed time: 1.01612 msecs"
)

0 comments on commit b5edaa7

Please sign in to comment.