euclid的扩展算法C ++

时间:2012-10-10 18:37:43

标签: c++ algorithm

我遇到了Euclid扩展算法的问题。 (ax + by = gcd(a,b))我试图确定GCD和x和y。 GCD不是问题,但使用循环方法x和y出错了。通常一个数字为0,另一个数字为异常大的负数。代码如下:

#include <iostream>

using namespace std;

main ()
{
    int a,b,q,x,lastx,y,lasty,temp,temp1,temp2,temp3;
    cout << "Please input a" << endl;
    cin >> a; 
    cout << "Please input b" << endl;
    cin >> b;
    if (b>a) {//we switch them
        temp=a; a=b; b=temp;
    }
    //begin function
    x=0;
    y=1;
    lastx=1;
    lasty=0;
    while (b!=0) {
        q= a/b;
        temp1= a%b;
        a=b;
        b=temp1;

        temp2=x-q*x;
        x=lastx-q*x;
        lastx=temp2;

        temp3=y-q*y;
        y=lasty-q*y;
        lasty=temp3;
    }

    cout << "gcd" << a << endl;
    cout << "x=" << lastx << endl;
    cout << "y=" << lasty << endl;
    return 0;
}

2 个答案:

答案 0 :(得分:10)

虽然很久以前就已经提出这个问题了,但答案会帮助那些正在寻找C ++实现扩展欧几里德算法的人。

这是一个递归的C ++实现:

int xGCD(int a, int b, int &x, int &y) {
    if(b == 0) {
       x = 1;
       y = 0;
       return a;
    }

    int x1, y1, gcd = xGCD(b, a % b, x1, y1);
    x = y1;
    y = x1 - (a / b) * y1;
    return gcd;
}

代码示例:

#include <iostream>

int main()
{
   int a = 99, b = 78, x, y, gcd;

   if(a < b) std::swap(a, b);

   gcd = xGCD(a, b, x, y);
   std::cout << "GCD: " << gcd << ", x = " << x << ", y = " << y << std::endl;

   return 0;
}

<强>输入:

a = 99,b = 78

<强>输出:

GCD:3,x = -11,y = 14

答案 1 :(得分:9)

你的两个作业应该是错的:

    temp2 = x;
    x=lastx-q*x;
    lastx = temp2;

    temp3 = y;
    y = lasty-q*y;
    lasty=temp3;

带有上述修复的示例输出:

Please input a
54
Please input b
24
gcd6
x=1
y=-2