Last active
August 29, 2015 14:12
-
-
Save RussellAndrewEdson/6166a4e21258f0d76669 to your computer and use it in GitHub Desktop.
Clojure code to generate the nth Fibonacci number in logarithmic time.
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
(defn fibonacci | |
"Returns the nth Fibonacci number using a logarithmic squaring algorithm." | |
[n] | |
(let [square (fn [x] (* x x))] | |
(loop [current 0N next 1N p 0N q 1N count n] | |
(cond (= count 0) current | |
(even? count) (recur current | |
next | |
(+ (square p) (square q)) | |
(+ (square q) (* 2 p q)) | |
(/ count 2)) | |
:else (recur (+ (* p current) (* q next)) | |
(+ (* q current) (* (+ p q) next)) | |
p | |
q | |
(dec count)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment