This is the first activity of Computerization algorithm team. We introduced the method to find the n n n th term of the Fibonacci sequence, which mainly uses matrix exponentiation.
Problemโ
The Fibonacci sequence:
F n = { 0 , n = 0 1 , n = 1 F n โ 2 + F n โ 1 , n > 1 F_{n}=
\begin{cases}
0,&n=0\\
1,&n=1\\
F_{n-2}+F_{n-1},&n>1
\end{cases} F n โ = โฉ โจ โง โ 0 , 1 , F n โ 2 โ + F n โ 1 โ , โ n = 0 n = 1 n > 1 โ Given n n n , find F n ย modย 1 0 9 + 7 F_{n}\text{ mod }10^9+7 F n โ ย modย 1 0 9 + 7 ใ
Input constraints Memory limit Execution time 0 โค n โค 1 0 19 0\le n\le 10^{19} 0 โค n โค 1 0 19 64MB 1.0s
Solutionโ
The input size of 1 0 19 10^{19} 1 0 19 obviously prohibits any attempt to solve it with loops. Is there a better way than a simple O ( n ) \mathcal{O}(n) O ( n ) ? It turns out that with matrix exponentiation , we can achieve O ( log โก n ) \mathcal{O}(\log n) O ( log n ) . We observe that:
( F n + 1 F n + 2 ) = ( F n + 1 F n + F n + 1 ) = ( 0 1 1 1 ) ( F n F n + 1 ) \begin{pmatrix}F_{n+1}\\F_{n+2}\end{pmatrix}=\begin{pmatrix}F_{n+1}\\F_{n}+F_{n+1}\end{pmatrix}=\begin{pmatrix}0&1\\1&1\end{pmatrix}\begin{pmatrix}F_{n}\\F_{n+1}\end{pmatrix} ( F n + 1 โ F n + 2 โ โ ) = ( F n + 1 โ F n โ + F n + 1 โ โ ) = ( 0 1 โ 1 1 โ ) ( F n โ F n + 1 โ โ )
This step is applicable to all recursive sequences, so it should be easily reached for an experienced candidate. Generally, for F n + 2 = a F n + b F n + 1 F_{n+2}=aF_{n}+bF_{n+1} F n + 2 โ = a F n โ + b F n + 1 โ , we have
( F n + 1 F n + 2 ) = ( F n + 1 a F n + b F n + 1 ) = ( 0 1 a b ) ( F n F n + 1 ) \begin{pmatrix}F_{n+1}\\F_{n+2}\end{pmatrix}=\begin{pmatrix}F_{n+1}\\aF_{n}+bF_{n+1}\end{pmatrix}=\begin{pmatrix}0&1\\a&b\end{pmatrix}\begin{pmatrix}F_{n}\\F_{n+1}\end{pmatrix} ( F n + 1 โ F n + 2 โ โ ) = ( F n + 1 โ a F n โ + b F n + 1 โ โ ) = ( 0 a โ 1 b โ ) ( F n โ F n + 1 โ โ )
From the recursive definition,
( F n + m F n + m + 1 ) = ( 0 1 1 1 ) m ( F n F n + 1 ) \begin{pmatrix}F_{n+m}\\F_{n+m+1}\end{pmatrix}=\begin{pmatrix}0&1\\1&1\end{pmatrix}^m\begin{pmatrix}F_{n}\\F_{n+1}\end{pmatrix} ( F n + m โ F n + m + 1 โ โ ) = ( 0 1 โ 1 1 โ ) m ( F n โ F n + 1 โ โ )
Substituting n = 0 n=0 n = 0 ,
( F m F m + 1 ) = ( 0 1 1 1 ) m ( F 0 F 1 ) \begin{pmatrix}F_{m}\\F_{m+1}\end{pmatrix}=\begin{pmatrix}0&1\\1&1\end{pmatrix}^m\begin{pmatrix}F_0\\F_1\end{pmatrix} ( F m โ F m + 1 โ โ ) = ( 0 1 โ 1 1 โ ) m ( F 0 โ F 1 โ โ )
Now the problem is transformed into finding the matrix raised to the m m m th power. If m = 2 0 a 0 + 2 1 a 1 + 2 2 a 2 + โฆ m=2^0a_0+2^1a_1+2^2a_2+\dots m = 2 0 a 0 โ + 2 1 a 1 โ + 2 2 a 2