题目链接:戳我
就是大力推式子,然后上BSGS就行了。
\[x_n\equiv a^{n-1}x_1+b(a^{n-2}+a^{n-3}+...+a)\pmod p\]
\[t\equiv a^{n-1}x_1+b\sum_{i=0}^{n-2}a^i\pmod p\]
\[t\equiv a^{n-1}x_1+b\times \frac{1\times(1-a^{n-1})}{1-a}\pmod p\]
\[t\equiv a^{n-1}x_1+\frac{b}{1-a}-\frac{b}{1-a}\times a^{n-1}\pmod p\]
\[t\equiv a^{n-1}(x_1-\frac{b}{1-a})+\frac{-b}{1-a}\pmod p\]
\[a^{n-1}\equiv \frac{-b+(1-a)\times t}{(1-a)\times 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\n");continue;}
else if(a==0)
{
if(b==t)printf("2\n");
else printf("-1\n");
continue;
}
else if(a==1)
{
if(b==0){printf("-1\n");continue;}
t=(t-x1+p)%p;
t=1ll*t*fpow(b,p-2,p)%p;
printf("%lld\n",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\n",cur+1);
}
}
return 0;
}
原文地址:https://www.cnblogs.com/fengxunling/p/10904345.html
时间: 2024-10-14 22:55:42