Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exercise 1.17 #12

Merged
merged 1 commit into from
Oct 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
)