zoukankan      html  css  js  c++  java
  • 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
    ");
            }
            else{
                x = x % m;
                if(x <= 0) x += m;
                printf("%lld
    ", x);
            }
        }
        return 0;
    }
  • 相关阅读:
    Oozie — What Why and How
    git 用户手册
    整理笔记 C语言
    第一次理解通用链表
    C++ 通用队列类
    懂了这些,你才真正懂了C
    简单键盘驱动
    简述进程间通信方式
    几何原本
    GSP几何画板简介
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9844430.html
Copyright © 2011-2022 走看看