Here is my way of finding the nth Fibonacci number:
(defn fib-pair [[a b]]
"Return the next Fibonacci pair number based on input pair."
[b (+' a b)]) ; Use +' for automatic handle large numbers (Long -> BigInt).
(defn fib-nth [x]
"Return the nth Fibonacci number."
(nth (map first (iterate fib-pair [0 1])) x))
I know this may be not the most efficient way, and I found the fast doubling algorithms.
The algorithm contains matrix and math equations, I don't know how to set them in Stack Overflow, please visit:
https://www.nayuki.io/page/fast-fibonacci-algorithms
I tried the Python implementation provided by that website, it is really fast. How to implement it in Clojure?
Edit: Python implementation provided by that website:
# Returns F(n)
def fibonacci(n):
if n < 0:
raise ValueError("Negative arguments not implemented")
return _fib(n)[0]
# Returns a tuple (F(n), F(n+1))
def _fib(n):
if n == 0:
return (0, 1)
else:
a, b = _fib(n // 2)
c = a * (2 * b - a)
d = b * b + a * a
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)