Skip to content

Instantly share code, notes, and snippets.

@bhugueney
Created June 4, 2013 21:45
Show Gist options
  • Save bhugueney/5709884 to your computer and use it in GitHub Desktop.
Save bhugueney/5709884 to your computer and use it in GitHub Desktop.
(defn fibonacci [n]
(letfn [(power-accumulate-positive [r a n op]
(let [r (if (odd? n) (op r a) r)]
( if (= 1 n) r (recur r (op a a) (bigint (/ n 2)) op))))
(power [a n op]
(if (odd? n)
(let [n (bigint (/ n 2))]
(if (zero? n) a (power-accumulate-positive a (op a a) n op)))
(recur (op a a) (bigint (/ n 2)) op)))
(fibonacci-matrix-multiply [[x0 x1] [y0 y1]]
[ (+ (* x0 (+ y1 y0)) (* x1 y0))
(+ (* x0 y0) (* x1 y1))])]
(if (zero? n) 0N)
(first (power [1N 0N] n fibonacci-matrix-multiply))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment