2 3 1 2013 2 3 2 2013 2 2 1 2013
4 14 4
看了题解,推公式。
A(n)=[(a+sqrt(b))^n],B(n)=[(a-sqrt(b))^n]
C(n)=A(n);
因为(a-1)2< b < a2,则B(n)属于(0,1);
C(n)=A(n)+B(n);
C(n)*(a+sqrt(b)+a-sqrt(b))=(a+sqrt(b))^(n+1)+(a-sqrt(b))(n+1)+(a*a-b)((a+sqrt(b))^(n-1)+(a-sqrt(b))(n-1));
即:
C(n)*2a=C(n+1)+(a*a-b)*C(n-1);
=>C(n+1)=2a*C(n)-(a*a-b)*C(n-1);
构造矩阵 :mat A(2,vec(2));
A[0][0]=2*a%m;
A[0][1]=(m-a*a%m+b)%m;
A[1][0]=1;
A[1][1]=0;
C(1)=2*a%m;
C(2)=2*(a*a%m+b)%m;
#include<cstdio> #include<algorithm> #include<cstring> #include<iostream> #include<string> #include<vector> #define ll long long using namespace std; ll a,b,n,m; typedef vector<ll>vec; typedef vector<vec>mat; mat mul(mat &A,mat &B) { mat C(A.size(),vec(B[0].size())); for(int i=0; i<A.size(); i++) { for(int k=0; k<B.size(); k++) { for(int j=0; j<B[0].size(); j++) { C[i][j]=(C[i][j]+A[i][k]*B[k][j])%m; } } } return C; } mat pow_mod(mat A,ll x) { mat B(A.size(),vec(A.size())); for(int i=0; i<A.size(); i++) { B[i][i]=1; } while(x>0) { if(x&1)B=mul(B,A); A=mul(A,A); x>>=1; } return B; } int main() { //freopen("test.in","r",stdin); while(~scanf("%I64d%I64d%I64d%I64d",&a,&b,&n,&m)) { if(n==1) { printf("%I64d\n",2*a%m); continue; } if(n==2) { printf("%I64d\n",2*(a*a%m+b)%m); continue; } mat A(2,vec(2)); A[0][0]=2*a%m; A[0][1]=(m-a*a%m+b)%m; A[1][0]=1; A[1][1]=0; A=pow_mod(A,n-2); ll ans=(A[0][0]*2*(a*a%m+b)%m+A[0][1]*2*a%m)%m; printf("%I64d\n",ans); } return 0; }
原文地址:http://blog.csdn.net/acm_baihuzi/article/details/45669061