BSGS算法(大步小步算法)
计算\(y^x ≡ z \ mod\ p\) 中 \(x\) 的解。
这个模板是最小化了\(x\) , 无解输出\(No \ Solution!\)
map<ll,ll>data;
ll m,res,t,ans; bool flag;
Pow(int x,int y,int p){return (x^y)%p;}
IL void BSGS(RG ll y , RG ll z,RG ll p){
y %=p;
flag = false;
if(!y && !z){puts("1");return;}
if(!y && z){puts("No Solution!"); return;}
data.clear();
//把z*(y^j)的值存下来
m = sqrt(p)+1; //一定要+1!!!!
for(RG ll j = 0; j <= m; j ++){
if(!j){res = z % p; data[res] = j; continue;}
res = res*y%p; if(!data[res])data[res] = j;
}
//计算y^(im)的值,与之前的值比对
t = Pow(y,m,p); res = 1;
for(RG ll i = 1; i <= m; i ++ ){
res = res*t%p;
if(data[res]){
ans = i*m - data[res];
ans = (ans%p+p)%p; cout<<ans<<endl;
flag = true; return;
}
}
if(!flag)puts("No Solution!");
}