Skip to content

Instantly share code, notes, and snippets.

@JasonGiedymin
Created May 12, 2011 03:28
Show Gist options
  • Save JasonGiedymin/967881 to your computer and use it in GitHub Desktop.
Save JasonGiedymin/967881 to your computer and use it in GitHub Desktop.
Fast Fibonacci
def bits(n):
'''Represent an integer as an array of binary digits.'''
bits = []
while n > 0:
n, bit = divmod(n, 2)
bits.append(bit)
bits.reverse()
return bits
def fib_fast(n):
''' Fast Fibonacci '''
assert n >= 0
a, b, c = 1, 0, 1
for bit in bits(n):
if bit: a, b = (a+c)*b, b*b + c*c
else: a, b = a*a + b*b, (a+c)*b
c = a + b
return b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment