题目描述 Description
给你6个数,m, a, c, x0, n, g
Xn+1 = ( aXn + c ) mod m,求Xn
m, a, c, x0, n, g<=10^18
输入描述 Input Description
一行六个数 m, a, c, x0, n, g
输出描述 Output Description
输出一个数 Xn mod g
样例输入 Sample Input
11 8 7 1 5 3
样例输出 Sample Output
2
/* 这个题显然用矩阵乘法,公式也很好推。 */ #include<cstdio> #include<iostream> #define lon long long using namespace std; lon m,a,c,x,n,g; struct node{ lon v[2][2]; }; lon Mul(lon s1,lon s2){//快速乘 lon r=0,base=s1; while(s2){ if(s2&1)r+=base; base+=base; r%=m; base%=m; s2>>=1; } return r; } node cheng(node s1,node s2){ node s3;s3.v[0][0]=s3.v[0][1]=s3.v[1][0]=s3.v[1][1]=0; for(int i=0;i<=1;i++) for(int j=0;j<=1;j++) for(int k=0;k<=1;k++){ s3.v[i][j]+=Mul(s1.v[i][k],s2.v[k][j]);//s1.v[i][k]*s2.v[k][j]; s3.v[i][j]%=m; } return s3; } node poww(node aa,lon bb){ node base=aa,r; r.v[0][0]=r.v[1][1]=1; r.v[0][1]=r.v[1][0]=0; while(bb){ if(bb&1)r=cheng(r,base); base=cheng(base,base); bb>>=1; } return r; } int main(){ cin>>m>>a>>c>>x>>n>>g; node s1,s2; s1.v[0][0]=x;s1.v[0][1]=1; s1.v[1][0]=0;s1.v[1][1]=0; s2.v[0][0]=a;s2.v[0][1]=0; s2.v[1][0]=c;s2.v[1][1]=1; node ans=poww(s2,n); ans=cheng(s1,ans); cout<<ans.v[0][0]%g; return 0; }
时间: 2024-10-07 04:37:28