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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP