第一次写关于模板的博客,可能是心血来潮吧。
矩阵相乘代码:
1 void Matrix(int (&a)[2][2],int b[2][2]){ 2 int tmp[2][2] = {0}; 3 for(int i = 0; i < 2; ++i) 4 for(int j = 0; j < 2; ++j) 5 for(int k = 0; k < 2; ++k) 6 tmp[i][j] = (tmp[i][j] + a[i][k] * b[k][j]) % N; 7 for(int i = 0; i < 2; ++i) 8 for(int j = 0; j < 2; ++j) 9 a[i][j] = tmp[i][j]; 10 }
普通快速幂代码:
1 //快速幂 (a^b)%mod 2 //如果求逆元,则b = mod-2; 3 ll pow_quick(ll a,ll b){ 4 ll r = 1,base = a; 5 while(b){ 6 if(b & 1){ 7 r *= base; 8 r %= mod; 9 } 10 base *= base; 11 base %= mod; 12 b >>= 1; 13 } 14 return r; 15 }
矩阵快速幂代码:
1 //矩阵快速幂定义全局变量 2 const ll maxn=1000+10; 3 const ll mod=1000000007; 4 const ll N = 2; 5 ll n = 0; 6 //定义一个矩阵 7 struct Matrix { 8 ll m[N][N]; 9 }; 10 11 //矩阵相乘 12 Matrix multi(Matrix a,Matrix b) { 13 Matrix c; 14 for(ll i=0; i<N; i++) { 15 for(ll j=0; j<N; j++) { 16 c.m[i][j]=0; 17 for(ll k=0; k<N; k++){ 18 c.m[i][j] += a.m[i][k]*b.m[k][j]%mod; 19 } 20 c.m[i][j]%=mod; 21 } 22 } 23 return c; 24 } 25 26 //矩阵快速幂 27 Matrix power(Matrix A,ll k) { 28 Matrix ans,p=A; 29 re(ans.m,0); 30 for(ll i = 0; i < N; i ++){ 31 ans.m[i][i] = 1; 32 } 33 while(k) { 34 if(k&1) { 35 ans=multi(ans,p); 36 k--; 37 } 38 k>>=1; 39 p=multi(p,p); 40 } 41 return ans; 42 } 43 int main() { 44 ll n; 45 while(~scanf("%lld",&n)) { 46 Matrix A = { 47 1,1, 48 1,0 49 }; 50 Matrix ans =power(A,n-1); 51 printf("%lld ",ans.m[0][0]); 52 } 53 return 0; 54 }