C++ 计算最大公约数的C++程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7549255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ program to calculate greatest common divisor
提问by user964141
I have started this program to calculate the greatest common divisor. This is what I have so far:
我已经启动了这个程序来计算最大公约数。这是我到目前为止:
#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;
}
I always get a 0 for the GCD. What am I doing wrong?
我总是得到 GCD 的 0。我究竟做错了什么?
采纳答案by James Black
You should be looping through to find this, and it may help if you put, with some equations, your algorithm for how this should work.
你应该循环查找这个,如果你用一些方程来说明你的算法应该如何工作,这可能会有所帮助。
But you have two problems I see, unless you are calling this inside of another loop.
但是我看到你有两个问题,除非你在另一个循环中调用它。
You are returning in both cases, either the if or else, so you only go through here once.
您在两种情况下都会返回,无论是 if 还是 else,所以您只经过这里一次。
Also, this part makes no sense, why modify the b
value after doing a return
?
另外,这部分没有意义,为什么b
在做了一个之后修改值return
?
return b;
b = b%a;
You should be using recursion for this, btw.
顺便说一句,您应该为此使用递归。
http://rosettacode.org/wiki/Greatest_common_divisor#Recursive_Euclid_algorithm
http://rosettacode.org/wiki/Greatest_common_divisor#Recursive_Euclid_algorithm
回答by noelyahan
int getGCD(int a, int b) {
//here we need to check if b == 0 return a
//这里我们需要检查b == 0是否返回a
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
Euclid's Algorithm Implementation
欧几里得算法实现