Skip to content

Instantly share code, notes, and snippets.

@RussellAndrewEdson
Created January 4, 2015 06:05
Show Gist options
  • Save RussellAndrewEdson/7ead2bfa3587f717c6a7 to your computer and use it in GitHub Desktop.
Save RussellAndrewEdson/7ead2bfa3587f717c6a7 to your computer and use it in GitHub Desktop.
Python code to generate the nth Fibonacci number in logarithmic time.
# 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