ZOJ 3609 Modular Inverse(扩展欧几里得)题解

时间:2023-03-09 05:06:04
ZOJ 3609 Modular Inverse(扩展欧几里得)题解

题意:求乘法逆元最小正正数解

思路:a*x≡1(mod m),则称x 是 a 关于 m 的乘法逆元,可以通过解a*x + m*y = 1解得x。那么通过EXGcd得到特解x1,最小正解x1 = x1 % m,如果x1 <=0,x1 += m,注意m是负数时取绝对值,因为是正解,所以不能用(x1%m+m)%m。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#define LS(n) node[(n)].ch[0]
#define RS(n) node[(n)].ch[1]
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int maxn = + ; ll ex_gcd(ll a, ll b, ll &x, ll &y){
ll d, t;
if(b == ){
x = ;
y = ;
return a;
}
d = ex_gcd(b, a%b, x, y);
t = x-a/b*y;
x = y;
y = t;
return d;
}
int main(){
ll a, m, x, y, T;
scanf("%lld", &T);
while(T--){
scanf("%lld%lld", &a, &m);
ll d = ex_gcd(a, m, x, y);
if( % d != ){
printf("Not Exist\n");
}
else{
x = x % m;
if(x <= ) x += m;
printf("%lld\n", x);
}
}
return ;
}