An iterative algorithm for Fibonacci numbers

后端 未结 13 1153
野性不改
野性不改 2020-11-28 10:37

I am interested in an iterative algorithm for Fibonacci numbers, so I found the formula on wiki...it looks straight forward so I tried it in Python...it doesn\'t have a prob

13条回答
  •  鱼传尺愫
    2020-11-28 11:27

    I came across this on another thread and it is significantly faster than anything else I have tried and wont time out on large numbers. Here is a link to the math.

    def fib(n):
        v1, v2, v3 = 1, 1, 0  
        for rec in bin(n)[3:]: 
            calc = v2*v2
            v1, v2, v3 = v1*v1+calc, (v1+v3)*v2, calc+v3*v3
            if rec=='1':    v1, v2, v3 = v1+v2, v1, v2
        return v2
    

提交回复
热议问题