题解:P3846 【模板】BSGS / [TJOI2007] 可爱的质数
lailai0916 · · 题解
参考资料
- 离散对数 - OI Wiki
题意简述
给定质数
解题思路
设
把
两侧分别枚举:
- 小步:枚举
j 从0 到m-1 ,将n\cdot b^{j} 连同j 存入哈希表; - 大步:枚举
i 从1 到m ,算出b^{im} 查表,命中即得l=im-j 。
若有解,最小解必小于
时间复杂度为
参考代码
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
ll bsgs(ll b,ll n,ll p)
{
b%=p;
n%=p;
if(n==1||p==1)return 0;
ll m=ceil(sqrt((double)p)),cur=n;
unordered_map<ll,ll> mp;
for(ll j=0;j<m;j++)
{
mp[cur]=j;
cur=cur*b%p;
}
ll t=1;
for(ll i=0;i<m;i++)t=t*b%p;
cur=1;
for(ll i=1;i<=m;i++)
{
cur=cur*t%p;
if(mp.count(cur))return i*m-mp[cur];
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll p,b,n;
cin>>p>>b>>n;
ll res=bsgs(b,n,p);
if(res==-1)cout<<"no solution"<<'\n';
else cout<<res<<'\n';
return 0;
}