2

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

X J
  • 3
  • 1
user67341
  • 29
  • 1

1 Answers1

2

Here are two suggestions:

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.

It is possible that a similar approach works more generally.

Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514