Skip to content

Instantly share code, notes, and snippets.

@Hermann-SW
Created May 11, 2021 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hermann-SW/7e99567ed50e98f7e1fc850d01c6e819 to your computer and use it in GitHub Desktop.
Save Hermann-SW/7e99567ed50e98f7e1fc850d01c6e819 to your computer and use it in GitHub Desktop.
fibmod(n,m)[0] returns n-th nfibonacci number "mod m" -- in linear time [in O(log(n))] for constant m
from sys import argv
#
def calc(t, m, odd):
return ((t[1]**2 + t[0]**2 ) % m, (t[1]**2 + 2*t[0]*t[1]) % m) if odd\
else ((t[1]**2 - (t[1]-t[0])**2) % m, (t[1]**2 + t[0]**2 ) % m)
#
def fibmod(n, m):
if n==0:
return (0, 1)
elif n==1:
return (1, 1)
else:
return calc(fibmod(n//2, m), m, n%2 == 1)
#
print( fibmod(int(argv[1]), int(argv[2])) [0] )
#
@Hermann-SW
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment