I'm trying to write a program with an input of numbers $n$ and $k$ (where $n<10^{20}$ and $k<10^9$), where I compute fib[n] % k. What is a good FAST way of computing this?
I have read many articles on this topic. At first I wanted to use a Pisano period. However, there is no formula to calculate the Pisano period.
Then I wanted to calculate Fibonacci number. However, it does not fit into any type of standard data type (Fibo(1000000000000000000) has about 208987640249978720 decimal).
I see this matrix formula: $$\begin{pmatrix} 1&1\\\ 1&0 \end{pmatrix}^n= \begin{pmatrix} F_{n+1}&F_n\\\ F_n&F_{n-1} \end{pmatrix} $$
However, according to the second issue, I can not save the result.
I feel that I am missing some theory. I'll be glad for any help.
The fastest way is somewhere around $O(\log^2 n)$. It is highly related to the matrix, but uses a little "recycling". This examples how to find $F_k$ I will explain the modding last.
Take note of these basic properties of Fibonacci numbers:
With these properties we can double the position of a Fibonacci number's index, instead of going one by one, which makes it so much faster.
Steps:
Example:
Optimizations: