题目描述:
求密钥哇.
题目分析:
K=Ba
K
=
B
a
ga≡A(modp)
g
a
≡
A
(
mod
p
)
现在我们需要求解出a,上面的那个式子很明显就是BSGS的形式,套用BSGS即可求出
预处理
gi
g
i
的值,用map存一下
题目链接:
Ac 代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <map>
#include <cmath>
#define ll long long
std::map<ll,ll> a;
ll mod,g,m;
int t;
inline void init()
{
ll x=1;
a[1]=0;
for(ll i=1;i<=m;i++)
{
x=(x*g)%mod;
a[x]=i;
}
}
inline void exgcd(ll a,ll b,ll &d,ll &x,ll &y)
{
if(!b) d=a,x=1,y=0;
else exgcd(b,a%b,d,y,x),y-=x*(a/b);
}
inline ll inv(ll x)
{
ll d,xx,y;
exgcd(x,mod,d,xx,y);
return d==1?(xx+mod)%mod:-1;
}
inline ll fastpow(ll x,ll y)
{
ll ans=1;
for(;y;y>>=1,x=(x*x)%mod)
if(y&1) ans=(ans*x)%mod;
return ans;
}
inline ll BSGS(ll x)
{
for(ll i=0;i<=m;i++)
{
ll val=(x*inv(fastpow(g,i*m)))%mod;
if(a.count(val)) return i*m+a[val];
}
return -1;
}
int main()
{
scanf("%lld%lld",&g,&mod);
m=std::ceil(sqrt(mod));
init();
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
ll A,B;
scanf("%lld%lld",&A,&B);
printf("%lld\n",fastpow(B,BSGS(A)));
}
return 0;
}