The title is not difficult to understand. The formula is a recursive, and it is not difficult to find F[n] is a power of the whole number. (F[1]=a0;f[2]=ab;f[3]=ab*f[2]c*f[1] ...)
Let's look at the index section first, set H[n]. The
h[1]=0;
H[2]=b;
H[3]=B+H[2]*C+H[1];
H[n]=b+h[n-1]*c+h[n-1].
H[n] is a recursive formula of three numbers, so it can be converted to a 3x3 matrix multiplied by the 3x1 matrix. So
H[n] C 1 B h[n-1]
H[n-1] = 1 0 0 * h[n-2]
1 0 0) 1 1
Also according to the Fermat theorem (Ap-1%p=1,p is prime and A,p coprime) is available: ah[n]%mod=ah[n]% (mod-1)%mod.
Because ah[n]%mod= ax* (mod-1) +h[n]% (mod-1)%mod = ax* (mod-1) *ah[n]% (mod-1)%mod = ah[n]% (mod-1)%mod;
#include <iostream>#include<cstdio>#include<cstring>using namespaceStd;typedefLong LongLl;ll p;structmat{ll mat[3][3];}; Mat Multiply (Mat A, Mat b) {mat C; memset (C.mat,0,sizeof(C.mat)); for(intK =0; K <3; ++k) for(inti =0; I <3; ++i)if(A.mat[i][k]) for(intj =0; J <3; ++j)if(B.mat[k][j]) c.mat[i][j]= (C.mat[i][j] +a.mat[i][k] * b.mat[k][j])% (P-1); returnC;} Mat Quickpower (Mat A, ll K) {Mat C; memset (C.mat,0,sizeof(C.mat)); for(inti =0; I <3; ++i) c.mat[i][i]=1; for(; k; k >>=1) { if(k&1) C =Multiply (c,a); A=Multiply (a,a); } returnC;} ll Powermod (ll A,ll b) {a%=p; ll ans=1; for(; b; b>>=1) { if(b&1) ans= (ans*a)%p; A= (a*a)%p; } returnans;}intMain () {//freopen ("In.txt", "R", stdin); intT; scanf ("%d",&T); ll N,a,b,c; Mat x; while(t--) {scanf ("%i64d%i64d%i64d%i64d%i64d",&n,&a,&b,&c,&p); if(n==1) printf ("1\n"); Else if(n==2) printf ("%i64d\n", Powermod (A, b)); Else{x.mat[0][0]=c; x.mat[0][1]=1; x.mat[0][2]=b; x.mat[1][0]=1; x.mat[1][1]=0; x.mat[1][2]=0; x.mat[2][0]=0; x.mat[2][1]=0; x.mat[2][2]=1; X=quickpower (x,n-2); ll K= (x.mat[0][0]*b+x.mat[0][2]); printf ("%i64d\n", Powermod (a,k)); } } return 0;}
HDU 5667 Sequence Matrix fast Power + Fermat theorem