the first is a little basic knowledge:
① matrix multiplication rule: matrix multiplication with matrix the number of columns in the first matrix must equal the number of rows in the second matrix if the first is the M*n matrix and the second is the n*p matrix, the result is the m*p matrix and the elements in the matrix have the following characteristics:
The first column is the product of each element of the first row of the first matrix and each element of the first column of the second matrix, and so on line I the element in the J column is the sum of the product of each element in row I of the first matrix and each element of the second matrix, j column.
② Unit matrix: N*n Matrix Mat (i, i) = 1; any matrix multiplied by the unit matrix is itself n the unit matrix =n, the unit matrix can be equivalent to an integer 1. (The unit matrix is used in the Matrix fast Power)
For example, the following figure is a 7*7 unit matrix:
The realization of matrix and its multiplication:
See http://blog.csdn.net/g_congratulation/article/details/52734281
for the relationship between matrix multiplication and recurrence:
In the Fibonacci sequence,
Fi[i] = 1*fi[i-1]+1*fi[i-2] fi[i-1] = 1*f[i-1] + 0*f[i-2];
That
So
Matrix fast Power:
Because the matrix multiplication satisfies the binding law, the reason is as follows
So, we can solve the fast power of the matrix by using a kind of algorithm like the fast power of numbers. (Prerequisite: Matrix is n*n matrix, cause see matrix multiplication definition)
Code
Matrix Fast_pow (Matrix A, int x) {
matrix ans;
Ans.x = a.x;
for (int i = 0; i < ans.x i++)
ans.a[i][i] = 1;
while (x) {
if (x&1)
ans = ans*a;
A = A*a;
x >>= 1;
}
return ans;
}
The code for the nth item of the Fibonacci sequence is obtained by fast power of the matrix:
#include <cstdio> #include <algorithm> #include <cstring> #include <iostream> using namespace
Std
const int M = 1E9+7;
struct Matrix {long long a[2][2];
Matrix () {memset (A, 0, sizeof (a));
Matrix operator * (const matrix y) {matrix ans; for (int i = 0; I <= 1; i++) for (int j = 0; J <= 1; j +) for (int k = 0; k <= 1; k++) Ans.a[i][j] =
A[I][K]*Y.A[K][J];
for (int i = 0; I <= 1; i++) for (int j = 0; J <= 1; j +) Ans.a[i][j]%= M;
return ans; } void operator = (const Matrix b) {for (int i = 0; I <= 1; i++) for (int j = 0; J <= 1; j +) A[i][j] = B.A I
[j];
}
};
int solve (long long x) {Matrix ans, TRS;
Ans.a[0][0] = ans.a[1][1] = 1;
Trs.a[0][0] = trs.a[1][0] = trs.a[0][1] = 1;
while (x) {if (x&1) ans = ans*trs;
TRS = Trs*trs;
x >>= 1;
return ans.a[0][0];
int main () {int n;
scanf ("%d", &n);
cout << Solve (n-1) << Endl;
return 0; }