Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 980 Accepted Submission(s): 315
Problem Description
Holion August will eat every thing he has found.
Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.
fn=⎧⎩⎨⎪⎪1,ab,abfcn−1fn−2,n=1n=2otherwise
He gives you 5 numbers n,a,b,c,p,and he will eat fn foods.But there are only p foods,so you should tell him fn mod p.
Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.
fn=⎧⎩⎨⎪⎪1,ab,abfcn−1fn−2,n=1n=2otherwise
He gives you 5 numbers n,a,b,c,p,and he will eat fn foods.But there are only p foods,so you should tell him fn mod p.
Input
The first line has a number,T,means testcase.
Each testcase has 5 numbers,including n,a,b,c,p in a line.
1≤T≤10,1≤n≤1018,1≤a,b,c≤109 , p is a prime number,and p≤109+7 .
Each testcase has 5 numbers,including n,a,b,c,p in a line.
1≤T≤10,1≤n≤1018,1≤a,b,c≤109 , p is a prime number,and p≤109+7 .
Output
Output one number for each case,which is
fn
mod p.
Sample Input
1 5 3 3 3 233
Sample Output
190
Source
Recommend
wange2014
(
a
b)
p[n]= a
b * ((a
b)
p[n-1])
c * ((a
b)
p[n-2]);递推式子可以这样写;
合并后变为(a
b)
p[n]=(a
b)
(c*p[n-1]+p[n-2]+1);
可以得到p[n]=c*p[n-1]+p[n-2]+1;
则可以构造矩阵
p[n] c 1 1 p[n-1]
p[n-1]
= 1 0 0 * p[n-2]
1 0 0 1 1
费马小定理 a(p-1)Ξ1%p 可以转化为ax%(p-1) =ax %p
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#define INF 0x3f3f3f3f
using namespace std;
#define MAXN 10005
#define MAXM 50005
long long a,b,c,mod;
typedef struct
{
long long m[3][3];
} Mat;
Mat A= {1,0,0,
0,1,0,
0,0,1,
};
long long Num_quick_pow(long long a,long long n)
{
long long ans=1;
while(n)
{
if(n&1)ans=ans*a%mod;
a=a*a%mod;
n>>=1;
}
return ans;
}
Mat Mat_Mul(Mat a,Mat b)
{
Mat ans;
for(int i=0; i<3; ++i)
for(int j=0; j<3; ++j)
{
ans.m[i][j]=0;
for(int k=0; k<3; ++k)
ans.m[i][j]=(ans.m[i][j]+a.m[i][k]*b.m[k][j]%(mod-1))%(mod-1);
}
return ans;
}
long long Mat_quick_pow(Mat P,long long n)
{
Mat Ans=A;
while(n)
{
if(n&1)Ans=Mat_Mul(Ans,P);
P=Mat_Mul(P,P);
n>>=1;
}
return (Ans.m[0][0]*b%(mod-1)+Ans.m[0][2]*b%(mod-1))%(mod-1);
}
int main()
{
int T;
long long n;
scanf("%d",&T);
while(T--)
{
scanf("%I64d%I64d%I64d%I64d%I64d",&n,&a,&b,&c,&mod);
if(n==1)
{
printf("1\n");
continue;
}
if(n==2)
{
printf("%I64d\n",Num_quick_pow(a,b));
continue;
}
Mat C= {c,1,1,
1,0,0,
0,0,1
};
if(a%mod==0)printf("0\n");
else cout<<Num_quick_pow(a,Mat_quick_pow(C,n-2))<<endl;
}
return 0;
}