Created
January 4, 2015 06:05
-
-
Save RussellAndrewEdson/7ead2bfa3587f717c6a7 to your computer and use it in GitHub Desktop.
Python code to generate the nth Fibonacci number in logarithmic time.
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
# Calculates the nth Fibonacci number using a logarithmic algorithm. | |
def fibonacci(n): | |
# Helper function: returns True if n is an even number. | |
even = lambda n: (n % 2 == 0) | |
(current, next, p, q) = (0, 1, 0, 1) | |
while (n > 0): | |
if (even(n)): | |
(p, q) = (p**2 + q**2, q**2 + 2*p*q) | |
n /= 2 | |
else: | |
(current, next) = (p*current + q*next, q*current + (p+q)*next) | |
n -= 1 | |
return current |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment