擴展歐幾里得

模板
#include <iostream>
#include <cstdio>
#define LL long long
using namespace std;

void ext_Gcd(LL a, LL b, LL &x, LL &y)   //a * x + b * y = 1; a * x = 1 (mod b);  a, b互素有唯一解,否則無解;
{
    if (b == 0)
    {
        x = 1;
        y = 0;

        return;
    }

    ext_Gcd(b, a % b, y, x);

    y -= a / b * x;
}

LL Ext_GCD(LL a, LL b, LL& x, LL& y)   //a * x + b * y = d; d = gcd(a, b);
{  
    if(b == 0)  
    {  
        x = 1;
        y = 0;  
        return a;  
    }

    LL d = Ext_GCD(b, a % b, x, y);  
    LL temp = x;  
    x = y;  
    y = temp - a / b * y;  

    return d;  
}  

int main()
{
    LL a, b, x, y;

    while (scanf("%lld%lld", &a, &b))
    {
        ext_Gcd(a, b, x, y);
        cout << x << ' ' << y << endl;

        LL d = Ext_GCD(a, b, x, y);
        cout << d << ' ' << x << ' ' << y << endl;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章