我正在尝试实现一个递归函数来计算两个数字的 gcd,但我的代码无法正常工作,知道出了什么问题吗?
public static int gcd(int a, int b) {
if (a == b) {
return a;
}
while (a != b) {
if (a > b) {
gcd(a - b, b);
} else if (b > a) {
gcd(a, b - a);
}
}
return a;
}
最佳答案
如果使用递归,则不需要 while 循环。只要这样做:
public static int gcd(int a, int b) {
if (a == b) {
return a;
}
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
顺便说一句,while (a != b)
如果达到的话就是无限循环。
关于java - 计算最大公约数的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33586147/