Skip to content

Commit

Permalink
Fully tail-recursive implementation of a ** b.
Browse files Browse the repository at this point in the history
  • Loading branch information
Andreas Krüger authored and Andreas Krüger committed Jul 16, 2012
1 parent de8c9fe commit 4ec0110
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions chapter1/src/chapter1/sqrt/ReallyGoodSQRT.clj
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,19 @@

;; I could have used the one from Math,
;; (defn power [x n] (Math/pow x n))
;; but, for the fun of it, here is the pedestrian way:

(defn power [x n]
(cond
(< n 0) (recur (/ 1.0 x) (- n))
(= n 0) 1.0
(= 1 (rem n 2)) (* x (power (* x x) (quot n 2)))
true (recur (* x x) (quot n 2))))
;; but, for the fun of it, here is the pedestrian way
;; (for integral numbers n only):

(defn power
; Return x**n:
([x n] (power x n 1.0))
; Return z * x**n:
([x n z]
(cond
(< n 0) (recur (/ 1.0 x) (- n) z)
(= n 0) z
(= 1 (rem n 2)) (recur (* x x) (quot n 2) (* z x))
true (recur (* x x) (quot n 2) z))))

;; To find some approximate start value
;; that is higher than the true value,
Expand Down

0 comments on commit 4ec0110

Please sign in to comment.