Advertisement
jules0707

fibonacci_last_digit_large_number

Jun 1st, 2017
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. # Uses python3
  2. import sys
  3.  
  4. # too slow memory exceeded
  5. def get_fibonacci_last_digit_naive(n):
  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 % 10
  16.  
  17. # faster solution only storing the last digit
  18. def fib_last_digit_large_number(n):
  19.     if n <= 1:
  20.         return n
  21.  
  22.     l = [0, 1]
  23.     i = 2
  24.  
  25.     while i < n + 1:
  26.         # stores only the last unit digit of every number which turns out is all you need
  27.         # to compute the next addition
  28.         l.append((l[i - 1] + l[i - 2]) % 10)
  29.         i += 1
  30.  
  31.     return l[n]
  32.  
  33.  
  34. if __name__ == '__main__':
  35.     # user_input = sys.stdin.read()
  36.     n = int(input())
  37.     print(fib_last_digit_large_number(n))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement