Fast Fibonacci computation

前端 未结 4 1796
失恋的感觉
失恋的感觉 2021-02-04 17:56

I saw a comment on Google+ a few weeks ago in which someone demonstrated a straight-forward computation of Fibonacci numbers which was not based on recursion and didn\'t use mem

4条回答
  •  悲&欢浪女
    2021-02-04 18:29

    Since Fibonacci sequence is a linear recurrence, its members can be evaluated in closed form. This involves computing a power, which can be done in O(logn) similarly to the matrix-multiplication solution, but the constant overhead should be lower. That's the fastest algorithm I know.

    EDIT

    Sorry, I missed the "exact" part. Another exact O(log(n)) alternative for the matrix-multiplication can be calculated as follows

    from functools import lru_cache
    
    @lru_cache(None)
    def fib(n):
        if n in (0, 1):
            return 1
        if n & 1:  # if n is odd, it's faster than checking with modulo
            return fib((n+1)//2 - 1) * (2*fib((n+1)//2) - fib((n+1)//2 - 1))
        a, b = fib(n//2 - 1), fib(n//2)
        return a**2 + b**2
    

    This is based on the derivation from a note by Prof. Edsger Dijkstra. The solution exploits the fact that to calculate both F(2N) and F(2N-1) you only need to know F(N) and F(N-1). Nevertheless, you are still dealing with long-number arithmetics, though the overhead should be smaller than that of the matrix-based solution. In Python you'd better rewrite this in imperative style due to the slow memoization and recursion, though I wrote it this way for the clarity of the functional formulation.

提交回复
热议问题