1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| #include<algorithm> #include<cstring> #include<cstdio> #include<vector> #include<queue> #include<unordered_map> using namespace std; using ll=long long; using pli=pair<ll,int>; using pi=pair<int,int>; template<typename A> using vc=vector<A>; inline int read() { int s=0,w=1;char ch; while((ch=getchar())>'9'||ch<'0') if(ch=='-') w=-1; while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar(); return s*w; } ll a,b,s,g,mod; ll qow(ll a,int b) { ll ans=1; while(b) { if(b&1) ans=ans*a%mod; a=a*a%mod; b>>=1; } return ans; } inline int BSGS(ll a,ll b) { int sq=1; for(;(sq+1)*(sq+1)<=mod;sq++); unordered_map<ll,int>vis; ll num=qow(a,sq),now=1; for(int i=0;i*sq<=mod;i++) { if(!vis.count(now)) vis[now]=i; now=now*num%mod; } int ans=0x3f3f3f3f; now=b,num=qow(a,mod-2); for(int i=0;i<sq;i++) { if(vis.count(now)) ans=min(ans,vis[now]*sq+i); now=now*num%mod; } if(ans==0x3f3f3f3fll) return -1; return ans; } int main() { int T=read(); while(T--) { mod=read(),a=read(),b=read(),s=read(),g=read(); if(s==g) { printf("0\n"); continue; } if(a==1) { if(b!=0) printf("%lld\n",(g-s+mod)*qow(b,mod-2)%mod); else printf("-1\n"); continue; } if(a==0) { if(b==g) printf("1\n"); else printf("-1\n"); continue; } ll num=(a*s-s+b+mod)%mod; if(num==0) { printf("-1\n"); continue; } printf("%d\n",BSGS(a,(a*g-g+b+mod)%mod*qow(num,mod-2)%mod)); } return 0; }
|