扩展的欧几里得算法只是计算两个数字的GCD的另一种方法。它具有额外的变量来计算ax + by = gcd(a,b)。在计算机程序中使用效率更高
Begin Declare variable a, b, x and y gcdExtended(int a, int b, int *x, int *y) if (a == 0) *x = 0; *y = 1; return b; Take two variables to store the result Update x and y using results of recursive call End
#include <bits/stdc++.h>
using namespace std;
int gcdExtended(int a, int b, int *x, int *y) {
if (a == 0) {
*x = 0;
*y = 1;
return b;
}
int x1, y1;
int gcd = gcdExtended(b%a, a, &x1, &y1);
*x = y1 - (b/a) * x1;
*y = x1;
return gcd;
}
int main() {
int x, y;
int a = 35, b = 15;
cout<<"gcd "<<gcdExtended(a, b, &x, &y);
return 0;
}输出结果
gcd 5