Top

矩阵快速幂模板


快速幂函数

1
2
3
4
5
6
7
8
9
10
11
12
ll quick_mod(ll a,ll b,ll c) //快速幂计算(a^b)%c
{
ll ans = 1;
while(b)
{
if(b&1) //相当于b%2==1
ans = (ans*a)%c;
a = (a*a)%c;
b>>=1; //相当于b/=2
}
return ans;
}

矩阵快速幂模版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<bits/stdc++.h> 
using namespace std;
int N=7;
void Matrix(int (&a)[2][2],int b[2][2]){
int tmp[2][2]={0};
for(int i=0;i<2;++i)
for(int j=0;j<2;++j)
for(int k=0;k<2;++k)
tmp[i][j]=(tmp[i][j]+a[i][k]*b[k][j])%N;
for(int i=0;i<2;++i){
for(int j=0;j<2;++j){
a[i][j]=tmp[i][j];
}
}
}
int main(){
int a,b,n;
while(scanf("%d%d%d",&a,&b,&n)){
if(a==0&&b==0&&n==0)break;
if(n==1){
cout<<1<<endl;
continue;
}
int temp[2][2]={a,b,0,0},cot[2][2]={1,0,0,1}, x[2] = {1, 1};
n-=2;
while(n){
if(n&1)Matrix(cot,temp);
Matrix(temp,temp);
n/=2;

}
int ans=0;
for(int i=0;i<2;i++)
ans=(ans+x[i]*cot[0][i])%N;
cout<<ans<<endl;
}
}


未经允许不得转载: Anoyer's Blog » 矩阵快速幂模板