fork download
#!/usr/bin/env python3
def sicpfib(n):
    """Compute nth fibonacci number. 
    
    O(log(n)) steps, O(n) in memory (to hold the result)
    
    Function Fib(count)
        a ← 1
        b ← 0
        p ← 0
        q ← 1
        While count > 0 Do
            If Even(count) Then
                 p ← p² + q²
                 q ← 2pq + q²
                 count ← count ÷ 2
            Else
                 a ← bq + aq + ap
                 b ← bp + aq
                 count ← count - 1
            End If
        End While
        Return b
    End Function
    See http://stackoverflow.com/questions/1525521/nth-fibonacci-number-in-sublinear-time/1526036#1526036
    """
    a, b, p, q = 1, 0, 0, 1
    while n > 0:
        if n % 2 == 0: # even
            oldp = p
            p = p*p + q*q
            q = 2*oldp*q + q*q
            n //= 2
        else:
            olda = a
            a = b*q + a*q + a*p
            b = b*p + olda*q
            n -= 1
    return b
    
print(*[sicpfib(i) for i in range(10)])
Success #stdin #stdout 0s 9992KB
stdin
Standard input is empty
stdout
0 1 1 2 3 5 8 13 21 34