【发布时间】:2014-12-14 04:19:59
【问题描述】:
这是我找到第 n 个斐波那契数的方法:
(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))
我知道这可能不是最有效的方法,我找到了快速加倍算法。
该算法包含矩阵和数学方程,我不知道如何在Stack Overflow中设置它们,请访问:
https://www.nayuki.io/page/fast-fibonacci-algorithms
我试过那个网站提供的Python实现,速度真的很快。如何在 Clojure 中实现?
编辑:该网站提供的 Python 实现:
# 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)
【问题讨论】: