Fast Fibonacci recursion

前端 未结 9 1663

I\'m trying to recall an algorithm on Fibonacci recursion. The following:

public int fibonacci(int n)  {
  if(n == 0)
    return 0;
  else if(n == 1)
    ret         


        
9条回答
  •  太阳男子
    2020-12-07 23:53

    You can do a pretty fast version of recursive Fibonacci by using memoization (meaning: storing previous results to avoid recalculating them). for example, here's a proof of concept in Python, where a dictionary is used for saving previous results:

    results = { 0:0, 1:1 }
    
    def memofib(n):
        if n not in results:
            results[n] = memofib(n-1) + memofib(n-2)
        return results[n]
    

    It returns quickly for input values that would normally block the "normal" recursive version. Just bear in mind that an int data type won't be enough for holding large results, and using arbitrary precision integers is recommended.

    A different option altogether - rewriting this iterative version ...

    def iterfib(n):
        a, b = 0, 1
        for i in xrange(n):
            a, b = b, a + b
        return a
    

    ... as a tail-recursive function, called loop in my code:

    def tailfib(n):
        return loop(n, 0, 1)
    
    def loop(i, a, b):
        if i == 0:
            return a
        return loop(i-1, b, a+b)
    

提交回复
热议问题