Advertisement
jules0707

fibonacci_sum

Jun 12th, 2017
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. # Uses python3
  2. import sys
  3.  
  4.  
  5. def fibonacci_sum_naive(p):
  6.     if p <= 1:
  7.         return p
  8.  
  9.     previous = 0
  10.     current = 1
  11.     sumFib = 1
  12.  
  13.     for _ in range(p - 1):
  14.         previous, current = current, previous + current
  15.         sumFib += current
  16.  
  17.     return sumFib % 10
  18.  
  19.  
  20. def get_fibonacci_huge_naive(n, m):
  21.     if n <= 1:
  22.         return n
  23.  
  24.     previous = 0
  25.     current = 1
  26.  
  27.     for _ in range(n - 1):
  28.         previous, current = current, previous + current
  29.  
  30.     return current % m
  31.  
  32.  
  33. #  property of the Fibonacci remainders of modulo n operation is that you can find the next remainder by adding
  34. #  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
  35. #  also the pattern of remainders repeat every time you encounter the a 0 followed by a 1. That is the mark for the
  36. #  length of the Pisano period.
  37.  
  38.  
  39. def get_fibonacci_huge_faster(p, q):
  40.     if p <= 1:
  41.         return p
  42.  
  43.     previous = 1
  44.     current = 1
  45.     pisanoPeriod = 1
  46.  
  47.     while (previous, current) != (0, 1):
  48.         #  we loop back on q to get the remainder of the remainders sum
  49.         previous, current = current, (previous + current) % q
  50.         pisanoPeriod += 1
  51.     # we just need to find the remainder of p when divided by the Pisano period.
  52.     #  numbers are small enough now to use the naive approach
  53.     return get_fibonacci_huge_naive(p % pisanoPeriod, q)
  54.  
  55.  
  56. # turns out that Sum(F(0->i)) = F(i+2) % 10 - 1
  57. def fib_sum_faster(p):
  58.     res = get_fibonacci_huge_faster(p + 2, 10) - 1
  59. # we loop back on 10
  60.     if res == -1:
  61.         res = 9
  62.     return res
  63.  
  64.  
  65.  
  66.  
  67. if __name__ == '__main__':
  68.     user_input = sys.stdin.read()
  69.     n = int(user_input)
  70.     print(fib_sum_faster(n))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement