Advertisement
jules0707

fibonacci_huge

Jun 9th, 2017
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. # Uses python3
  2. import sys
  3.  
  4.  
  5. def get_fibonacci_huge_naive(n, m):
  6.     if n <= 1:
  7.         return n
  8.  
  9.     previous = 0
  10.     current = 1
  11.  
  12.     for _ in range(n - 1):
  13.         previous, current = current, previous + current
  14.  
  15.     return current % m
  16.  
  17.  
  18. #  property of the Fibonacci remainders of modulo n operation is that you can find the next remainder by adding
  19. #  the last 2 and looped on n ie. for F(13) mod 5 , r(13) = r(11) + r(12) = 4 + 4 =  3 because 8 = 5 + 3
  20. #  also the pattern of remainders repeat every time you encounter the a 0 followed by a 1. That is the mark for the
  21. #  length of the Pisano period.
  22.  
  23.  
  24. def get_fibonacci_huge_faster(p, q):
  25.     if p <= 1:
  26.         return p
  27.  
  28.     previous = 1
  29.     current = 1
  30.     pisanoPeriod = 1
  31.  
  32.     while (previous, current) != (0, 1):
  33.         #  we loop back on q to get the remainder of the remainders sum
  34.         previous, current = current, (previous + current) % q
  35.         pisanoPeriod += 1
  36.     #  we just need to find the remainder of p when divided by the Pisano period.
  37.     #  numbers are small enough now to use the naive approach
  38.     return get_fibonacci_huge_naive(p % pisanoPeriod, q)
  39.  
  40.  
  41. if __name__ == '__main__':
  42.     user_input = sys.stdin.read()
  43.     a, b = map(int, user_input.split())
  44.     # print(get_fibonacci_huge_naive(a, b))
  45.     print(get_fibonacci_huge_faster(a, b))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement