Code:
#include<cstdio> #include<algorithm> using namespace std; long long n,p,q,a1,a2,mod; struct matrix{ long long c[2][2]; }; matrix I={1,0,0,1}; matrix A={0,0,0,0}; matrix R={0,1,0,0}; matrix operator*(matrix a,matrix b){ matrix C=A; for(int i=0;i<2;++i) for(int j=0;j<2;++j) for(int k=0;k<2;++k) C.c[i][j]=(C.c[i][j]+(a.c[i][k]*b.c[k][j])%mod)%mod; return C; } matrix pow(matrix a,long long k){ matrix ans=I; while(k){ if(k&1)ans=ans*a; a=a*a;k/=2; } return ans; } int main(){ scanf("%lld %lld %lld %lld %lld %lld",&p,&q,&a1,&a2,&n,&mod); if(n==1){printf("%lld",a1%mod);return 0;} if(n==2){printf("%lld",a2%mod);return 0;} matrix fin=A; fin.c[0][0]=a2; fin.c[0][1]=a1; matrix M=R; M.c[0][0]=p; M.c[1][0]=q; matrix ans=fin*pow(M,n-2); printf("%lld",ans.c[0][0]); return 0; }