题目链接:戳我
就是大力推式子,然后上BSGS就行了。
[x_nequiv a^{n-1}x_1+b(a^{n-2}+a^{n-3}+...+a)pmod p
]
[tequiv a^{n-1}x_1+bsum_{i=0}^{n-2}a^ipmod p
]
[tequiv a^{n-1}x_1+b imes frac{1 imes(1-a^{n-1})}{1-a}pmod p
]
[tequiv a^{n-1}x_1+frac{b}{1-a}-frac{b}{1-a} imes a^{n-1}pmod p
]
[tequiv a^{n-1}(x_1-frac{b}{1-a})+frac{-b}{1-a}pmod p
]
[a^{n-1}equiv frac{-b+(1-a) imes t}{(1-a) imes x_1-b}pmod p
]
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#define int long long
#define MAXN 1010
using namespace std;
int T;
map<int,int>ex;
inline int fpow(int x,int y,int mod)
{
int cur_ans=1;
while(y)
{
if(y&1) cur_ans=1ll*cur_ans*x%mod;
x=1ll*x*x%mod;
y>>=1;
}
return cur_ans;
}
inline int inv(int x,int mod){return fpow(x,mod-2,mod);}
inline int bsgs(int x,int y,int mod)
{
x%=mod,y%=mod;
ex.clear();
int m=ceil(sqrt(mod));
for(int i=0,t=1;i<m;i++,t=1ll*t*x%mod)
if(!ex.count(t)) ex[t]=i;
for(int i=0,tt=inv(fpow(x,m,mod),mod),cur=y;i<m;i++,cur=1ll*cur*tt%mod)
if(ex.count(cur))
return i*m+ex[cur];
return -2;
}
signed main()
{
#ifndef ONLINE_JUDGE
freopen("ce.in","r",stdin);
freopen("ce.out","w",stdout);
#endif
scanf("%lld",&T);
while(T--)
{
int a,p,x1,t,b;
// cout<<endl;
scanf("%lld%lld%lld%lld%lld",&p,&a,&b,&x1,&t);
if(x1==t){printf("1
");continue;}
else if(a==0)
{
if(b==t)printf("2
");
else printf("-1
");
continue;
}
else if(a==1)
{
if(b==0){printf("-1
");continue;}
t=(t-x1+p)%p;
t=1ll*t*fpow(b,p-2,p)%p;
printf("%lld
",t+1);
continue;
}
else
{
// cout<<((t-b*inv(1-a,p))%p+p)%p<<endl;
// cout<<((t-b*inv(1-a,p))%p+p)%p*inv(((x1-b*inv(1-a,p))%p+p)%p,p)<<endl;
int cur=bsgs(a,((t-b*inv(1-a,p))%p+p)%p*inv(((x1-b*inv(1-a,p))%p+p)%p,p),p)%p;
printf("%lld
",cur+1);
}
}
return 0;
}