I am trying to create a function that gives me the fibonacci sequence for any value of n. However, after the n = 92, I am getting incorrect answers.
eg. For n = 93
Expected output = 12200160415121876738
Actual Output = -6246583658587674878
My code is below:
import numpy as np
def Power(M, n):
if not n:
return 1
elif n % 2:
return M*Power(M, n-1)
else:
sqrt = Power(M, n//2)
return sqrt**2
def _fib(n):
G = np.matrix([[1,1],[1,0]])
F = Power(G, n)
return F[0,1]
I think it has something to do with integer overflow related to the limitation of the matrix library. I am not sure how to fix it. Please help me out. I would prefer if this algorithm is improved upon.