# Is there any efficient way of calculating the n-th fibonacci number modulo another number?

With efficient I mean of a big O of polynomial time in the number of digits each number has.

• Any general number or a prime? Have you seen this? What have you tried so far? – Evil Mar 5 '17 at 22:50
• If you want to find the $n$th fibonacci number, doesn't your time complexity have to depend on $n$ as well? – Riley Mar 5 '17 at 23:22
• If you mean literally what you wrote, then fixing the modulus would mean you'd have to be able to calculate arbitrary Fibonacci numbers in constant time. That can't be possible, since the Fibonacci sequence, even modulo something, isn't eventually constant. – David Richerby Mar 5 '17 at 23:46
• cs.stackexchange.com/q/37571/755, cs.stackexchange.com/q/62401/755 - you can adapt the techniques there to your problem, by just doing all calculatiosn modulo the modulus. – D.W. Mar 6 '17 at 3:45
• It appears you may have created multiple accounts. If so, I encourage you to merge them. This will help you retain the ability to edit your question and comment on answers. – D.W. Mar 6 '17 at 3:46

The linear algebra approach. It is known that $$\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n = \begin{bmatrix} F_{n+1} & F_n \\ F_n &F_{n-1} \end{bmatrix}.$$ You can compute the matrix power using repeated squaring, doing all the calculations modulo your modulus.
Closed form. If your modulus is odd and 5 is a quadratic residue (i.e., 5 has a modular square root) then you can use the explicit formula $$F_n = \frac{\left(\frac{1+\sqrt{5}}{2}\right)^n - \left(\frac{1-\sqrt{5}}{2}\right)^n}{\sqrt{5}}.$$ You can then use Carmichael's function to reduce $n$, and then repeated squaring. Care must be taken when the modulus isn't a prime power.