zoukankan      html  css  js  c++  java
  • 51nod 125乘法逆元 (扩展欧几里得)

    给出2个数M和N(M < N),且M与N互质。找出一个数K满足0 < K < N且K * M % N = 1,假设有多个满足条件的。输出最小的。
    Input
    输入2个数M, N中间用空格分隔(1 <= M < N <= 10^9)
    Output
    输出一个数K。满足0 < K < N且K * M % N = 1。假设有多个满足条件的。输出最小的。
    Input演示样例
    2 3
    Output演示样例
    2

    思路:

    对于正整数。假设有。那么把这个同余方程中的最小正整数解叫做的逆元。

     

    逆元一般用扩展欧几里得算法来求得,假设为素数。那么还能够依据费马小定理得到逆元为

     

    推导步骤例如以下

                                

    #include <iostream>
    #include <cstdio>
    #include <string>
    #include <cstring>
    #include <fstream>
    #include <algorithm>
    #include <cmath>
    #include <queue>
    #include <stack>
    #include <vector>
    #include <map>
    #include <set>
    #include <iomanip>
    
    using namespace std;
    #pragma comment(linker, "/STACK:102400000,102400000")
    #define maxn 1000005
    #define MOD 1000000007
    #define mem(a , b) memset(a , b , sizeof(a))
    #define LL long long
    #define ULL long long
    const long long INF=0x3fffffff;
    
    void exc_gcd(LL a , LL b , LL &d , LL &x , LL &y)
    {
        if(b == 0)
        {
            x = 1 ;
            y = 0 ;
            d = a;
        }
        else
        {
            exc_gcd(b ,a % b , d , y , x);
            y -= x * (a/b);
        }
    }
    //ofstream  ofile;
    int main()
    {
        int n , m;
        while(scanf("%d %d",&m , &n) != EOF && m)
        {
            LL x , y , d;
            exc_gcd(m , n , d , x , y);
            x /= d;
            y /= d;
            LL t1 = n / d;
            LL t2 = m / d;
            x = (x % t1 + t1) % t1;
            cout << x << endl;
        }
        return 0;
    }
    






  • 相关阅读:
    UIButton 动态改变文本闪烁问题
    利用GDataXML解析XML文件
    限制键盘只能输入数字
    获得view所在的控制器
    使用Canvas绘制简单的时钟控件
    Spring整合ActiveMq消息队列
    Symmetric Key Encryption DES
    OSPF 高级实验
    OSPF 基础实验
    EIGRP 高级实验
  • 原文地址:https://www.cnblogs.com/yfceshi/p/7247338.html
Copyright © 2011-2022 走看看