【问题标题】:How to implement this fast doubling Fibonacci algorithm in Clojure?如何在 Clojure 中实现这种快速加倍斐波那契算法?
【发布时间】: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)

【问题讨论】:

    标签: clojure fibonacci


    【解决方案1】:

    我没有检查性能,但这似乎是 Clojure 中的忠实实现:

    (defn fib [n]
      (letfn [(fib* [n]
                (if (zero? n)
                  [0 1]
                  (let [[a b] (fib* (quot n 2))
                        c (*' a (-' (*' 2 b) a))
                        d (+' (*' b b) (*' a a))]
                    (if (even? n)
                      [c d]
                      [d (+' c d)]))))]
        (first (fib* n))))
    

    【讨论】:

    • 谢谢!该代码有效。我是 Clojure 的新手,一些对其他人来说容易的概念对我来说可能很难。我仍然需要更多地了解它。顺便说一句,由于前缀算术运算符,我仍然需要一些习惯性的工作来阅读数学方程式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2019-06-26
    相关资源
    最近更新 更多