矩阵快速幂笔记

快速幂求斐波那契数列

 1 //答案对100000007取模 
 2 #include<iostream>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cmath>
 6 #define MOD 100000007
 7 using namespace std;
 8 typedef long long ll;
 9 struct sq{
10     ll sq[2][2];
11     void mes(){
12         memset(sq,0,sizeof(sq));
13     }
14 };
15 sq operator *(sq a,sq b){
16     sq tmp;
17     tmp.mes();
18     for(int i=0;i<2;i++){
19         for(int j=0;j<2;j++){
20             for(int k=0;k<2;k++){
21                 tmp.sq[i][j]=(tmp.sq[i][j]+a.sq[i][k]*b.sq[k][j])%MOD;
22             }
23         }
24     }
25     return tmp;
26 }
27 ll fi(int n){
28     sq ans,m;
29     ans.mes();
30     m.mes();
31     m.sq[0][0]=m.sq[0][1]=m.sq[1][0]=1;
32     m.sq[1][1]=0;
33     ans.sq[0][0]=ans.sq[1][1]=1;
34     ans.sq[0][1]=ans.sq[1][0]=0;
35     while(n){
36         if(n&1){
37             ans=ans*m;
38         }
39         m=m*m;
40         n>>=1;
41     }
42     return ans.sq[0][1]%MOD;
43 }
44 int main(){
45     int n;
46     scanf("%d",&n);
47     printf("%lld",fi(n));
48     return 0;
49 }
原文地址:https://www.cnblogs.com/dcdcbigbig/p/8952566.html