实现扩展欧几里得算法的C ++程序
扩展的欧几里得算法只是计算两个数字的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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短