zoukankan      html  css  js  c++  java
  • [ZOJ 3609] Modular Inverse

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4712

    求a对于m的最小正整数逆元
    先回顾一下几个定理
    • 定理一:如果d = gcd(a, b),则必能找到正的或负的整数 x 和 y ,使 d = ax+ by。
    • 定理二:若gcd(a, b) = 1,则方程ax ≡ c (mod b)在[0, b-1]上有唯一解。
    • 定理三:若gcd(a, b) = d,则方程ax ≡ c (mod b)在[0, b/d - 1]上有唯一解。

    对于ax+by=1; 即ax=1(mod b) 当且仅当gcd(a,b)!=1 的时候,无解!

    AC代码:

    #include <iostream>
    #include <cstdio>
    
    using namespace std;
    
    int test;
    int a, b;
    
    //拓展欧几里得模板
    int extgcd(int a, int b, int &x, int &y) {
        int ans, temp;
        if(b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        ans = extgcd(b, a % b, x, y);
        temp = x;
        x = y;
        y = temp - a / b * y;
        return ans;
    }
    
    int main() {
        scanf("%d", &test);
        int x, y;
        while(test--) {
            scanf("%d%d", &a, &b);
            int ans = extgcd(a, b, x, y);
            if(ans != 1)
                printf("Not Exist
    ");
            else {
                x %= b;
                if(x <= 0)  //要求最小正整数,所以 x==0 也要考虑
                    x += b;
                printf("%d
    ", x);
            }
        }
        return 0;
    }
    
  • 相关阅读:
    输入分隔符
    GO
    match|align|identify|cover_rate
    KEGG
    InterProScan
    Functional annotation
    GeneWise
    get middle lines
    goland debug web app with urfave cli
    go mod proxy
  • 原文地址:https://www.cnblogs.com/youpeng/p/10807450.html
Copyright © 2011-2022 走看看