Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Created December 19, 2014 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanplopes/c07051282560f286dc8e to your computer and use it in GitHub Desktop.
Save juanplopes/c07051282560f286dc8e to your computer and use it in GitHub Desktop.
Fibonacci in O(log n)
def mul(A, B):
return (A[0]*B[0] + A[1]*B[2], A[0]*B[1] + A[1]*B[3],
A[2]*B[0] + A[3]*B[2], A[2]*B[1] + A[3]*B[3])
def fib(n):
if n==1: return (1, 1, 1, 0)
A = fib(n>>1)
A = mul(A, A)
if n&1: A = mul(A, fib(1))
return A
for n in range(1, 128):
print(fib(n)[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment