Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1916 Accepted Submission(s): 638
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.
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
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
题意:给出公式,求Fn。
思路:我们可以把 F [ 1 ] 看作是a^b的0次方,把 F [ 2 ] 看作是a^b的一次方,F [ n ] = a^b 的 n - 1 次方,这样一来我们可以列出等式 (a^b)^(n - 1) = (a^b)^( (n - 2) * c + (n - 3) + 1),我们可以对 a 的指数用矩阵快速幂求解,化简可得 Fn = Fn-1*c + Fn-2 + b ,需要注意的是 a 的指数太大,需要用欧拉降幂优化一下。
#include <bits/stdc++.h>
using namespace std;
const int N = 3 ;
long long n,a,b,c,p;
struct xx
{
long long a[N][N];
} ori;
xx mul(xx x,xx y)
{
xx temp;
memset(temp.a,0,sizeof(temp.a));
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
for(int k=0; k<N; k++)
{
temp.a[i][j]+=x.a[i][k]*y.a[k][j]%p;
}
}
}
return temp;
}
void inti()
{
int f[][N]={c,1,0,1,0,0,b,0,1};
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
ori.a[i][j]=f[i][j];
}
}
}
xx calc(long long k)
{
xx b;
memset(b.a,0,sizeof(b.a));
for(int i=0; i<3; i++)
b.a[i][i]=1;
while(k)
{
if(k%2==1)
{
b=mul(ori,b);
k-=1;
}
else
{
ori=mul(ori,ori);
k/=2;
}
}
return b;
}
long long Pow(long long a, long long b)
{
a %= p;
long long ans = 1ll;
while (b)
{
if (b & 1)ans = ans*a%p;
a = a*a%p;
b >>= 1;
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld%lld%lld%lld",&n,&a,&b,&c,&p);
if(n==1) printf("1\n");
else if(n==2) printf("%lld\n",Pow(a,b));
else
{
inti();
p--;
xx C=calc(n-2);
p++;
long long tmp=C.a[0][0]*b+C.a[2][0];
long long ans=Pow(a,tmp)%p;
printf("%lld\n",ans);
}
}
}