Last active
August 29, 2015 14:18
-
-
Save jgke/92d83933f6e18d336eca to your computer and use it in GitHub Desktop.
Fibonacci modulo m
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 _fibonacci(n, modulo): | |
if n == 0: | |
return (0, 1) | |
# get F(n/2) and F(n/2+1) | |
a, b = _fibonacci(n//2, modulo) | |
# F(n/2 + 1)*2 - F(n/2) might be negative because of the modulo | |
t = b*2 - a | |
if t < 0: | |
t += modulo | |
c = a * t | |
d = a ** 2 + b ** 2 | |
c %= modulo | |
d %= modulo | |
# return F(n) and F(n+1) | |
if n % 2: | |
return (d, c+d) | |
return (c, d) | |
def fibonacci(n, modulo): | |
# _fibonacci returns F(n) and F(n+1) | |
return _fibonacci(n, modulo)[0] | |
if __name__ == "__main__": | |
print("F(5):", fibonacci(5, 1000)) | |
print("F(5) modulo 10:", fibonacci(5, 10)) | |
print("F(1000000) modulo 12345:", fibonacci(1000000, 12345)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment