Input
Integers 'n' (up to 10^14) and 'm'(up to 10^3)
Output
Fib(n) modulo m
Sample Cases
Input: 239 1000 Output: 161 Input: 2816213588 239 Output: 151
Hint given in Question
As it is not possible to iterate 'n' times (because n is huge), consider using Pisano Period(repetition of remainders when every element Fibonacci series is divided by any integer)
Code which I wrote (maybe wrong, but passes above-mentioned cases)
n, m = map(int, input().split())
a, b = 0, 1
fib_rems = [0, 1] # remainders after diving 'm'
fib = [0, 1] # regular fibonacci series
while True:
a, b = b, a+b # cotinuing to grow Fibonacci series
fib.append(b)
fib_rems.append(b%m)
# checking if last two items in remainder are 0, 1 which is indication to pisano period
if fib_rems[-2] == 0 and fib_rems[-1] == 1:
# remving last two items in fib and fib_rems which are 1 and 0 so we get length equivalet excatly one period
fib_rems.pop()
fib_rems.pop()
fib.pop()
fib.pop()
break
period = len(fib_rems)
rem = n % period
print(fib[rem]%m)
The first thing I did is found out the Pisano period(length of repetition of remainders) and have confusion in the rest of the parts.
- Why fib(n=2015) mod 3 is equivalent to fib(7) mod 3? (for = 3 the period is 01120221 and has length 8 and 2015=251*8 + 7)
- In general, after getting the remainder sequence, how(mathematical proof) it is used for computing Fib(n) mod m?
- Can I improve/optimize the above code?
(In short, I don't understand last two lines of above code)
Any hints/guidance/reference/solution is greatly appreciated!