欧几里得的扩展算法C++
euclid's extended algorithm C ++
我在欧几里得的扩展算法上遇到了问题。(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;
}
虽然这个问题很久以前就被问过了,但答案将帮助那些正在寻找扩展欧几里得算法实现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
你的两个作业是错误的,它们应该是:
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
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 基于ELO的团队匹配算法
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 扩展光电二极管探测器以支持多个传感器
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 算法问题:查找从堆栈中弹出的所有序列
- 下面是排序算法O(n)吗
- 如何在源代码中使用执行策略检测 C++17 的扩展内存管理算法的可用性?
- 控制两个顶点之间的中间点数量 - 布雷森汉姆算法的扩展
- 欧几里得的扩展算法C++
- 扩展 Dijkstra 算法实现
- 在 c++ 中扩展欧几里得算法的递归中究竟发生了什么?
- 扩展GCD算法
- 高效搜索算法的文件与指定扩展名C/ c++