#include <iostream>
#include <cstdio>
using namespace std;
/**
a * x ≡ 1(mod m)
求最小的正的乘法逆元
s = m / gcd(a, m)
x = x0 + s * t
x = (x % s + s) % s
当x为负时
x % s = x - x / s * s
HINT:
if x == 0
x = s;
*/
int exgcd(int a, int b, int &x, int &y)
{
if (b == 0)
{
x = 1;
y = 0;
return a;
}
int r = exgcd(b, a % b, x, y);
int temp = x;
x = y;
y = temp - a / b * y;
return r;
}
int main()
{
//freopen("in.txt", "r", stdin);
int t, a, m, x, y, g;
scanf("%d", &t);
while (t--)
{
scanf("%d %d", &a, &m);
g = exgcd(a, m, x, y);
if (g != 1)
{
printf("Not Exist\n");
continue;
}
int s = m / g;
int ans = (x % s + s) % s;
if (ans == 0)
ans = s;
printf("%d\n", ans);
}
}
zoj3609_Modular Inverse(扩展欧几里得/naked)
最新推荐文章于 2019-04-03 19:06:54 发布