是否存在 G = A x i + B G=Ax_i+B G=Axi+B ?已知 x 0 = S x_0 = S x0=S
很快可以推出一个公式,然后等比数列一下,就可以变成只剩下形如拔山盖世的公式。
分类讨论,考虑清楚所有可能情况,在bsgs中不会出现的。然后剩下就是模板解决的问题了。
比如,什么时候解是0,如果除了个0会怎样。A=0和A=1这些边界条件下有什么特殊情况?
参考代码,转子
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;++i)
#define repn(i,n) for(int i=1;i<=n;++i)
#define LL long long
#define pii pair <int,int>
#define pb push_back
#define fi first
#define se second
#define mpr make_pair
#define MOD P
using namespace std;
LL t,P,A,B,S,G,lim;
map <LL,LL> mp;
LL qpow(LL x,LL a)
{
LL res=x,ret=1;
while(a>0)
{
if((a&1)==1) ret=ret*res%MOD;
a>>=1;
res=res*res%MOD;
}
return ret;
}
int main()
{
cin>>t;
rep(tn,t)
{
cin>>P>>A>>B>>S>>G;
if(S==G)
{
puts("0");
continue;
}
if(A==0)
{
if(B==G) puts("1");
else puts("-1");
continue;
}
if(A==1)
{
if(B==0)
{
puts("-1");
continue;
}
LL tmp=(G-S+P)%P;(tmp*=qpow(B,P-2))%=P;
cout<<tmp<<endl;
continue;
}
LL right=(G+B*qpow(A-1,P-2))%P,mul=(S+B*qpow(A-1,P-2))%P;
if(mul==0)
{
if(right==0)
{
puts("1");
continue;
}
puts("-1");
continue;
}
(right*=qpow(mul,P-2))%=P;
//A^ans = right
//bsgs
lim=ceil(sqrt((double)P));
mp.clear();
LL cur=1;
rep(i,lim)
{
LL res=right*cur%P;
if(mp.find(res)==mp.end()) mp[res]=i;
else mp[res]=max(mp[res],(LL)i);
(cur*=A)%=P;
}
LL bas=1;rep(i,lim) (bas*=A)%=MOD;
cur=bas;
LL ans=1e18;
repn(a,lim)
{
if(mp.find(cur)!=mp.end())
{
LL curres=(LL)a*lim-mp[cur];
if(curres<0) curres+=P-1;
curres%=(P-1);
ans=min(ans,curres);
}
(cur*=bas)%=P;
}
if(ans==1e18) puts("-1");
else cout<<ans<<endl;
}
return 0;
}