Fast Fibonacci computation

前端 未结 4 1863
失恋的感觉
失恋的感觉 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:36

    Using the weird square rooty equation in the other answer closed form fibo you CAN compute the kth fibonacci number exactly. This is because the $\sqrt(5)$ falls out in the end. You just have to arrange your multiplication to keep track of it in the meantime.

    def rootiply(a1,b1,a2,b2,c):
        ''' multipy a1+b1*sqrt(c) and a2+b2*sqrt(c)... return a,b'''
        return a1*a2 + b1*b2*c, a1*b2 + a2*b1
    
    def rootipower(a,b,c,n):
        ''' raise a + b * sqrt(c) to the nth power... returns the new a,b and c of the result in the same format'''
        ar,br = 1,0
        while n != 0:
            if n%2:
                ar,br = rootiply(ar,br,a,b,c)
            a,b = rootiply(a,b,a,b,c)
            n /= 2
        return ar,br
    
    def fib(k):
        ''' the kth fibonacci number'''
        a1,b1 = rootipower(1,1,5,k)
        a2,b2 = rootipower(1,-1,5,k)
        a = a1-a2
        b = b1-b2
        a,b = rootiply(0,1,a,b,5)
        # b should be 0!
        assert b == 0
        return a/2**k/5
    
    if __name__ == "__main__":
        assert rootipower(1,2,3,3) == (37,30) # 1+2sqrt(3) **3 => 13 + 4sqrt(3) => 39 + 30sqrt(3)
        assert fib(10)==55
    

提交回复
热议问题