So Easy!
代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h> #include<cstring> #define N 2 #define LL long long int m=2; LL MOD; struct Matrix{ LL matrix[N][N]; }; void init(Matrix &res) { for(int i=0;i<m;i++) { for(int j=0;j<m;j++) res.matrix[i][j]=0; res.matrix[i][i]=1; } } Matrix multiplicative(Matrix a,Matrix b) { Matrix res; memset(res.matrix,0,sizeof(res.matrix)); for(int i = 0 ; i <m; i++) for(int j = 0 ; j < m ; j++) for(int k = 0 ; k < m; k++) res.matrix[i][j] = (res.matrix[i][j]+a.matrix[i][k]%MOD*b.matrix[k][j]%MOD+MOD)%MOD; return res; } Matrix pow(Matrix mx,LL m) { Matrix res,base=mx; init(res); //初始为单位矩阵,即除主对角线都是1外,其他都是0 while(m) { if(m&1) res=multiplicative(res,base); base=multiplicative(base,base); m>>=1; } return res; } int main() { LL a,b,n; while(~scanf("%lld%lld%lld%lld",&a,&b,&n,&MOD)) { if(n==0) printf("%lld\n",2%MOD); else if(n==1) printf("%lld\n",2*a%MOD); else { Matrix base={ 2*a,-(a*a-b), 1,0 }; base=pow(base,n-1); printf("%lld\n",(2*a*base.matrix[0][0]%MOD+2*base.matrix[0][1]+MOD)%MOD); } } return 0; }