Another way is to only store the fibonacci number mod m, since fibonacci is modular consistant (because only an addition of terms and addition is modular consistant). Basically, given that
x1 = a1 * m + r1
x2 = a2 * m + r2
r1 + r2 = a3 * m + r3
are all euclidian divisions, then :
x1 + x2 = a1 * m + r1 + a2 * m + r2 = (a1 + a2) * m + (r1 + r2) = (a1 + a2 + a3) * m + r3
is the euclidian division of x1 + x2 (r3 is by definition the only number in [0, m-1] such that r1 + r2 = a3 * m + r3. You then add to both sides a multiple of m that doesn’t change the rest. The proof is pretty simple).
We therefore know that
x1 + x2 [mod m] = r3 = r1 + r2 [mod m]
and therefore only storing r1 and r2 (in your case, Fn mod m), is sufficient and the numbers will be less than m. basically, you’d write something like :
Fn+1 = (Fn + Fn-1) % m
I wrote it in python to test it, sure enough it works :
def fibo1(n, m):
l = [1, 1]
for i in range(n - 2):
l += [l[-1] + l[-2]]
l = [(v%m) for v in l]
return l
def fibo2(n, m):
l = [1, 1]
for i in range(n - 2):
l += [(l[-1] + l[-2])%m]
return l
print(fibo1(50, 6))
print(fibo2(50, 6))
Resulting in :
[1, 1, 2, 3, 5, 2, 1, 3, 4, 1, 5, 0, 5, 5, 4, 3, 1, 4, 5, 3, 2, 5, 1, 0, 1, 1, 2, 3, 5, 2, 1, 3, 4, 1, 5, 0, 5, 5, 4, 3, 1, 4, 5, 3, 2, 5, 1, 0, 1, 1]
[1, 1, 2, 3, 5, 2, 1, 3, 4, 1, 5, 0, 5, 5, 4, 3, 1, 4, 5, 3, 2, 5, 1, 0, 1, 1, 2, 3, 5, 2, 1, 3, 4, 1, 5, 0, 5, 5, 4, 3, 1, 4, 5, 3, 2, 5, 1, 0, 1, 1]
Anyways