c++程序计算最大公约数
C++ program to calculate greatest common divisor
我已经启动了这个程序来计算最大公约数。这是我目前所看到的:
#include <iostream>
#include <math.h>
using namespace std;
int getGCD(int a, int b)
{
a = a % b;
if (a == 0)
{
return b;
b = b % a;
}
if (b == 0)
{
return a;
}
}
int main()
{
int x, y;
cout << "Please enter two integers x and y, for GCD calculation" << endl;
cin >> x >> y;
cout << "The GCD of " << x << "and " << y << " is" << getGCD(x, y) << endl;
return 0;
}
我总是得到0的GCD。我做错了什么?
你应该通过循环找到这个,如果你用一些方程,你的算法应该如何工作,它可能会有所帮助。
但是我看到你有两个问题,除非你在另一个循环中调用这个。
在两种情况下都返回,要么是if,要么是else,所以这里只遍历一次。
同样,这部分也没有意义,为什么在做了return
之后还要修改b
的值呢?
return b;
b = b%a;
你应该使用递归,顺便说一下。
http://rosettacode.org/wiki/Greatest_common_divisor Recursive_Euclid_algorithm
int getGCD(int a, int b) {
//这里我们需要检查b == 0是否返回a
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
欧几里德算法实现
相关文章:
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 计算 PI 最多 42 位小数
- 如何修复我的最大公约数代码?它适用于除零和零以外的所有数字
- 有没有一种惯用的方法可以在不存储变换或不必要地重新计算的情况下找到数组变换的最小/最大值?
- 在 C++20 计算范围内相邻对的最简洁明了的方法是什么?
- 最大化双分区的 GCD(最大公约数)之和?
- 最大公因数函数
- 多项式最大公约数C++
- 实现欧几里得除法,根据两个正整数的线性组合编写这两个正整数的最大公约数
- 使用数组的 2 个数字的最大公约数
- 在编译时找到最大公约数
- 最常用的计算线-线交点的方法是C++
- C++最大公约数循环
- 直到n的所有数的最大公约数与n的和
- c++程序计算最大公约数
- 使用欧几里得算法识别两个值的最大公约数 (GCD)
- 找出最大公约数的程序
- 最有效的计算集合A对集合B的补的方法(向量)
- 最简单的计算对象实例的方法
- 最有效的计算字典索引的方法