Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1405 Accepted Submission(s): 461
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
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.
Output
Output one number for each case,which is fn
Sample Input
1 5 3 3 3 233
Sample Output
190
Source
对式子两边取对数 化简后会变成相加的递推式 在化成矩阵 由于矩阵是在指数上 所以需要模欧拉函数 又因为是质数 即p-1
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll n,a,b,c,Mod;
struct Matrix
{
ll ma[3][3];
void init()
{
memset(ma,0,sizeof(ma));
ma[0][1]=ma[1][0]=ma[2][1]=ma[2][2]=1;
}
}p;
Matrix Multi(Matrix a,Matrix b)
{
Matrix res;
memset(res.ma,0,sizeof(res.ma));
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
for(int k=0;k<3;k++)
res.ma[i][j]=(res.ma[i][j]+a.ma[i][k]*b.ma[k][j]%Mod)%Mod;
return res;
}
Matrix quick_pow(Matrix p,ll k)
{
Matrix res;
memset(res.ma,0,sizeof(res.ma));
for(int i=0;i<3;i++)
res.ma[i][i]=1;
while(k)
{
if(k&1)
res=Multi(res,p);
k>>=1;
p=Multi(p,p);
}
return res;
}
ll quick_pow(ll p,ll k)
{
ll res=1;
while(k)
{
if(k&1)
res=res*p%Mod;
k>>=1;
p=(p*p)%Mod;;
}
return res;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
p.init();
scanf("%lld%lld%lld%lld%lld",&n,&a,&b,&c,&Mod);
if(n==2)
{
printf("%lld\n",quick_pow(a,b));
continue;
}
else if(a%Mod==0)
{
puts("0");
continue;
}
Mod--;
p.ma[1][1]=c;
Matrix res;
memset(res.ma,0,sizeof(res.ma));
res=quick_pow(p,n-1);
ll ans=0;
ans=(b*res.ma[1][0]%Mod+b*res.ma[2][0]%Mod)%Mod;
Mod++;
printf("%lld\n",quick_pow(a,ans));
}
return 0;
}