How to write the Fibonacci Sequence?

前端 未结 30 2661
醉酒成梦
醉酒成梦 2020-11-22 00:32

I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 01:19

    Time complexity :

    The caching feature reduces the normal way of calculating Fibonacci series from O(2^n) to O(n) by eliminating the repeats in the recursive tree of Fibonacci series :

    enter image description here

    Code :

    import sys
    
    table = [0]*1000
    
    def FastFib(n):
        if n<=1:
            return n
        else:
            if(table[n-1]==0):
                table[n-1] = FastFib(n-1)
            if(table[n-2]==0):
                table[n-2] = FastFib(n-2)
            table[n] = table[n-1] + table[n-2]
            return table[n]
    
    def main():
        print('Enter a number : ')
        num = int(sys.stdin.readline())
        print(FastFib(num))
    
    if __name__=='__main__':
        main()
    

提交回复
热议问题