三个板子,注意bsgs的时候要特判无解,即a%p==0||b%p==0(bsgs还是很巧妙的。。)
码:
#include<iostream>
#include<cstdio>
#include<map>
#include<cmath>
using namespace std;
#define ll long long
map<ll,bool>ma;
map<ll,int>dui;
ll a,b,p,ans,x,y,i,j;
int T,k;
ll ksm(ll a,ll b)
{ll ans=1;
while(b)
{
if(b&1)ans=ans*a%p;
b/=2;
a=a*a%p;
}
return ans;
}
void exgcd(ll a,ll b)
{
if(!b)
{
y=0;
x=1;
ans=a;
return ;
}
exgcd(b,a%b);
ll t=x;
x=y;
y=t-a/b*y;
}
int main()
{
scanf("%d%d",&T,&k);
while(T--)
{
scanf("%lld%lld%lld",&a,&b,&p);
if(k==1)
{
printf("%lld\n",ksm(a,b));
}
if(k==2)
{
exgcd(a,p);
x=(x+p)%p;
if(b%ans==0)
{
printf("%lld\n",x*(b/ans)%p);
}else printf("Orz, I cannot find x!\n");
}
if(k==3)
{
if(b%p==0||a%p==0)
{
printf("Orz, I cannot find x!\n");
continue;
}
ll o=sqrt(p);
ma.clear();
dui.clear();
for(i=0;i<=o;i++)
{
ma[ksm(a,i)]=1;
dui[ksm(a,i)]=i;
}
bool yj=0;
for(i=0;i<=o;i++)
{
exgcd(ksm(a,i*o),p);
if(ma[(b*(x+p)%p+p)%p])
{
printf("%lld\n",i*o+dui[(b*(x+p)%p+p)%p]);
yj=1;break;
}
}
if(yj==0)
{
printf("Orz, I cannot find x!\n");
}
}
}
}