We write the series:
fibonacci[0] = 0,fibonacci[1] = 1
Fibonacci[n] = fibonacci[n-1] + fibonacci[n-2] (n >= 2)
it can be written in the form of matrix multiplication:
The right continuous expansion will be:
The following is the calculation of an O (log (n)) algorithm:
The code is as follows:
/* Solve any Fibonacci sequence value, enter an item to be calculated n, output the Fibonacci value corresponding to the item due to the large value, resulting in 1000000007 of the remainder */#include <iostream> #include <cstdio>
using namespace Std;
struct Matrix {__int64 a[2][2];};
Matrix E;
void inite (int size)//Initialize the unit matrix {for (int i=0;i<size;i++) {for (int j=0;j<size;j++) e.a[i][j]= (I==J);
}} Matrix Matrixmul (Matrix A,matrix B)//two matrix multiplied by {matrix C;
int i,j,k;
for (i=0;i<2;i++) {for (j=0;j<2;j++) {c.a[i][j]=0;
for (k=0;k<2;k++) {C.a[i][j] + = ((a.a[i][k]%1000000007) * (b.a[k][j]%1000000007));
c.a[i][j]%=1000000007;
}}} return C;
} Matrix Matrixpow (Matrix A,__int64 N)//matrix fast binary n power {matrix t=e;
while (n>0) {if (1&n)//n is an odd T=matrixmul (t,a);
A=matrixmul (A,a);
n >>= 1;
} return t;
} int main (void) {__int64 n;
Matrix matrix,m;
Inite (2); while (scanf ("%i64d", &n)!=eof) {if (n==1| |
n==2) printf ("1\n"); else {matrix.a[0][0]=1;
Constructs the initial matrix matrix.a[0][1]=1; Matrix.a[1][0]=1;
matrix.a[1][1]=0;
M=matrixpow (matrix,n-1);
printf ("%d\n", (M.a[0][0])%1000000007);
}} return 0; }
Screenshots are as follows: