An iterative algorithm for Fibonacci numbers

后端 未结 13 1158
野性不改
野性不改 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:28

    How about this simple but fastest way... (I just discovered!)

    def fib(n):
        x = [0,1]
        for i in range(n >> 1):
            x[0] += x[1]
            x[1] += x[0]
        return x[n % 2]
    

    Note! as a result, this simple algorithm only uses 1 assignment and 1 addition, since loop length is shorten as 1/2 and each loop includes 2 assignment and 2 additions.

提交回复
热议问题