Skip to content

Commit

Permalink
Exercise 1.16 (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
SmetDenis authored Oct 15, 2023
1 parent c68db1a commit ca08c3b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/sicp/chapter_1/ex_1_16.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
(ns sicp.chapter-1.ex-1-16)

; Exercise 1.16
; Design a procedure that evolves an iterative exponentiation process
; that uses successive squaring and uses a logarithmic number of steps, as does fast-expt.

; Hint:
; Using the observation that (b^(n/2))^2 = (b^2)^(n/2),
; keep, along with the exponent n and the base b, an additional state variable a,
; and define the state transformation in such a way that the product ab^n is unchanged from state to state.
; At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the
; process.
; In general, the technique of defining an invariant quantity that remains unchanged from
; state to state is a powerful way to think about the design of iterative algorithms.

(defn fast-expt
[b n product]
(cond (= n 0) product
(even? n) (fast-expt (* b b) (/ n 2) product)
:else (fast-expt b (- n 1) (* product b))))

(defn expt
[b n]
(fast-expt b n 1))
7 changes: 7 additions & 0 deletions test/sicp/chapter_1/ex_1_16_test.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
(ns sicp.chapter-1.ex-1-16-test
(:require [clojure.test :refer :all]
[sicp.chapter-1.ex-1-16 :refer [expt]]))

(deftest expt-test
(is (= 1 (expt 1 2)))
(is (= 3486784401 (expt 3 20))))

0 comments on commit ca08c3b

Please sign in to comment.