题目:
我是超链接
注意题目有问题,y,z,p中只有p为质数
题解:
这仿佛就是丁队说的三种情况
第一问快速幂
第二问是exgcd啊,这不是要求x非负吗,我就+p+p+p
第三问就是BSGS的裸题了,现在学了一下BSGS算法,下见普及向咯
代码:
#include <map>
#include <cmath>
#include <cstdio>
#include <iostream>
#define LL long long
using namespace std;
int T,k;LL y,z,p;
map<LL,LL> hash;
LL gcd(LL a,LL b){if (!b) return a;else return gcd(b,a%b);}
void exgcd(LL a,LL b,LL &x,LL &y){if (!b) x=1,y=0;else exgcd(b,a%b,y,x),y-=(a/b)*x;}
LL ksm(LL a,LL k,LL p)
{
LL ans=1;
for (;k;k>>=1,a=a*a%p)
if (k&1) ans=ans*a%p;
return ans%p;
}
void do1()
{
while (T--)
{
scanf("%lld%lld%lld",&y,&z,&p);
printf("%lld\n",ksm(y,z,p));
}
}
void do2()
{
while (T--)
{
scanf("%lld%lld%lld",&y,&z,&p);
LL d=gcd(y,p);
if (z%d!=0){printf("Orz, I cannot find x!\n");continue;}
y/=d;p/=d;z/=d;
LL x=0,yy=0;
exgcd(y,p,x,yy);
x=x*z%p;
while (x<0) x+=p;
printf("%lld\n",x);
}
}
LL bsgs(LL a,LL b,LL p)
{
if (gcd(a,p)!=1) return -1;
hash.clear();
LL m=ceil(sqrt(p));
LL am=ksm(a,m,p);
for (int j=0;j<=m;j++)
{
hash[b]=j;
b=b*a%p;
}
LL mul=1;
for (int i=1;i<=m;i++)
{
mul=mul*am%p;
if (hash[mul]) return i*m-hash[mul];
}
return -1;
}
void do3()
{
while (T--)
{
scanf("%lld%lld%lld",&y,&z,&p);
LL ans=bsgs(y,z,p);
if (ans==-1) printf("Orz, I cannot find x!\n");
else printf("%lld\n",ans);
}
}
int main()
{
scanf("%d%d",&T,&k);
if (k==1) do1();
if (k==2) do2();
if (k==3) do3();
}
普及向:
BSGS,北上广深算法,主要解决的是
Ax≡B(%C)
反正up主也写不出什么科学的笔记,还是直接链接
优秀的学姐