问题
ax≡b (mod p)
已知a,b,p求x
解法
令x=i*m-j (m=⌈c√⌉)
j(0~m) aj*b ->map
i(1~m) 若map中存在一个元素与a^mi%p相等则返回x
code
#include<cstdio>
#include<map>
#include<vector>
#include<cmath>
#include<climits>
#include<cstring>
typedef long long ll;
using namespace std;
#define f(x,y,z) for(int x=y;x<=z;x++)
ll p,m,a,b;
map<ll,ll> ma;
bool ok;
ll ksm(ll x,int y)
{
if(y==0)return 1;
ll t=ksm(x,y/2);
if(y%2==0)return t*t%p;
return t*t%p*x%p;
}
int main()
{
scanf("%lld",&p);
m=sqrt(p);
if(m*m<p)m++;
while(~scanf("%lld%lld",&a,&b))
{
ma.clear();
f(j,0,m)ma[(ksm(a,j)*b)%p]=j;
ok=0;
f(i,1,m)if(ma.find(ksm(a,m*i))!=ma.end())
{
ok=1;
printf("%lld\n",i*m-ma[ksm(a,m*i)]);
break;
}
if(!ok)printf("0\n");
}
return 0;
}
本文介绍了一种解决模指数方程 ax ≡ b (mod p) 的算法,该算法通过预计算和查找表的方式有效地寻找未知数 x 的值。在给定 a、b 和 p 的情况下,利用平方根大小的步长来减少搜索空间。

339

被折叠的 条评论
为什么被折叠?



