Skip to content

Instantly share code, notes, and snippets.

@RussellAndrewEdson
Last active August 29, 2015 14:12
Show Gist options
  • Save RussellAndrewEdson/6166a4e21258f0d76669 to your computer and use it in GitHub Desktop.
Save RussellAndrewEdson/6166a4e21258f0d76669 to your computer and use it in GitHub Desktop.
Clojure code to generate the nth Fibonacci number in logarithmic time.
(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