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 = 32767 + 10;

ll ex_gcd(ll a, ll b, ll &x, ll &y){
    ll d, t;
    if(b == 0){
        x = 1;
        y = 0;
        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(1 % d != 0){
            printf("Not Exist\n");
        }
        else{
            x = x % m;
            if(x <= 0) x += m;
            printf("%lld\n", x);
        }
    }
    return 0;
}

 

posted @ 2018-10-24 16:50  KirinSB  阅读(283)  评论(0编辑  收藏  举报