-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Denis Smet
committed
Oct 15, 2023
1 parent
ca08c3b
commit b5edaa7
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
) |