Created
May 12, 2011 03:28
-
-
Save JasonGiedymin/967881 to your computer and use it in GitHub Desktop.
Fast Fibonacci
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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