题意:已知x的递推式x(i+1) = (a*x(i)+b) % p,给定t, x1, a, b, p,求一个最小的n,使得x(n) = t. 0 <= a,b,x1,t <= p-1, 2 <= p <= 10^9.
分析:
首先我们不难得出通项x(n) = (a^(n-1) * x1 + b*(a^(n-1)-1)/(a-1)) % p.
然后设c为a-1在mod p意义下的逆元。
原题转化为求(x1+b*c)*a^(n-1) = b*c+t (mod p)的最小n.
通过exgcd(扩展欧几里得)求出a^(n-1).
然后BSGS,求出n-1即可。
下面来吐槽一下这道题坑人的地方:
1.p <= 10^9,int完全不够用,并且还要在各种地方mod p.
2.各种特判,a=0, a=1, b=0, x1=t.
3.少任何一个特判,你都会爆0,一分不得!!
#include <cstdio>
#include <map>
#include <cmath>
using namespace std;
typedef long long ll;
ll T,p,a,b,x1,t,g,x,y,ni;
void exgcd(ll a,ll b,ll &g,ll &x,ll &y) {if(!b) g=a,x=1,y=0;else exgcd(b,a%b,g,y,x),y-=(a/b)*x;}
ll pw(ll a, ll b) {
ll r = 1;
while(b) {if(b & 1) r = r*a%p; a = a*a%p, b >>= 1;}
return r;
}
ll bsgs(ll a, ll b) {
ll m = sqrt(p)+1, e = 1;
exgcd(pw(a, m), p, g, x, y);
ni = (x % p + p) % p;
map<ll, ll> mp;
mp[1] = 0;
for(int i = 1; i < m; i++) {
e = e*a%p;
if(!mp.count(e)) mp[e] = i;
}
for(int i = 0; i < m; i++) {
if(mp.count(b)) return i*m+mp[b];
b = b*ni%p;
}
return -2;
}
int main() {
scanf("%lld", &T);
while(T--) {
scanf("%lld%lld%lld%lld%lld",&p,&a,&b,&x1,&t);
if(x1 == t) {puts("1"); continue;}
if(!a) {printf("%d\n", b == t ? 2 : -1); continue;}
if(a == 1) {
if(!b) {puts("-1"); continue;}
exgcd(b, p, g, x, y);
x *= t-x1, x = (x % p + p) % p;
printf("%lld\n", x+1);
continue;
}
exgcd(a-1, p, g, x, y);
ni = (x % p + p) % p;
exgcd((x1+b*ni)%p, p, g, x, y);
if((b*ni+t) % g != 0) {puts("-1"); continue;}
x *= ((b*ni+t)/g)%(p/g), x = (x % (p/g) + p/g) % (p/g);
printf("%lld\n", bsgs(a, x)+1);
}
return 0;
}