zoukankan      html  css  js  c++  java
  • 数论:拓展欧几里得算法

    算法描述就是:

    求整数 x和y 使得 ax + by = 1.

    可以发现, 如果gcd(a, b) ≠ 1,则显然无解.

    反之, 如果gcd(a, b) = 1, 则可以通过拓展原来的 辗转相除法 来求解.

    事实上,一定存在整数对(x, y)使得ax+by = gcd(a,b) = 1

    代码如下:

    #include <iostream>
    using namespace std;
    
    int extgcd(int a, int b, int& x, int& y)
    {
        int d = a;
        if (b != 0)
        {
            d = extgcd(b, a % b, y, x);
            y -= (a / b) * x;
        } else {
            x = 1; y = 0;
        }
        return d;
    }
    
    void solve()
    {
        int x = 0, y = 0;
        int a, b;
        cin >> a >> b;
        int d = extgcd(a, b, x, y);
        cout << d << "=" << a << "*" << x << "+" << b << "*" << y << endl; 
    }
    
    int main()
    {
        solve();
        
        return 0;
    }

     

    题解:直接套用模板 

    #include <iostream>
    #include <cstdio>
    using namespace std;
    
    int extgcd(int a, int b, int& x, int& y)
    {
        int d = a;
        if (b != 0)
        {
            d = extgcd(b, a % b, y, x);
            y -= (a / b) * x;
        } else {
            x = 1; y = 0;
        }
        return d;
    }
    
    void solve()
    {
        int a = 97, b = 127;
        int x = 0, y = 0;
        int d = extgcd(a, b, x, y);
        cout << d << "=" << a << "*" << x << "+" << b << "*" << y << endl;
    }
    
    int main()
    {
        solve();
        
        return 0;
    }
  • 相关阅读:
    sss
    stm32cube使用
    FreeRTOS
    嵌入式网站
    CRC分段校验
    IAR编译器
    (转)UCOSII源代码剖析
    (转)stm32硬件IIC
    keil MDK注意事项
    (转).Net中自定义类作为Dictionary的key详解
  • 原文地址:https://www.cnblogs.com/douzujun/p/6662890.html
Copyright © 2011-2022 走看看