Java堆栈溢出错误
我正在尝试编写一个GCD算法,除了StackOverflower错误外,其他一切似乎都是正确的。代码如下:Java堆栈溢出错误,java,stack-overflow,Java,Stack Overflow,我正在尝试编写一个GCD算法,除了StackOverflower错误外,其他一切似乎都是正确的。代码如下: public class Gcd { public static BigInteger gcdNaive(BigInteger a, BigInteger b) { int res = a.compareTo(b); if ( res == 0 ) { BigInteger g = a; return
public class Gcd {
public static BigInteger gcdNaive(BigInteger a, BigInteger b) {
int res = a.compareTo(b);
if ( res == 0 ) {
BigInteger g = a;
return g;
}
else if ( res == 1 ) {
BigInteger h = a.subtract(b);
a = h;
return gcdNaive(a, b);
}
else if ( res == -1 ) {
BigInteger g = b.subtract(a);
b = g;
return gcdNaive(a, b);
}
return BigInteger.ZERO;
}
public static BigInteger gcdEuclid(BigInteger a, BigInteger b) {
if( b == BigInteger.ZERO ) {
BigInteger g = a;
return g;
}
else if ( b != BigInteger.ZERO ) {
BigInteger g = b;
BigInteger h = a.mod(b);
a = g;
b = h;
return gcdEuclid(a, b);
}
return BigInteger.ZERO;
}
}
例外情况:
Exception in thread "main" java.lang.StackOverflowError
at Gcd.gcdNaive(Gcd.java:7)
at Gcd.gcdNaive(Gcd.java:19)
gcdNaive的解决方案是:
public static BigInteger gcdNaive(BigInteger a, BigInteger b) {
int res = a.compareTo(b);
if(res == 0)
{
return b;
}
if(res == 1)
{
a = a.subtract(b);
return gcdNaive(a, b);
}
else
{
b = b.subtract(a);
return gcdNaive(a, b);
}
}
gcdEuclid的完整解决方案是
public static BigInteger gcdEuclid(BigInteger a, BigInteger b) {
if(b == BigInteger.ZERO)
{
return a;
}
return gcdEuclid(b, a.mod(b));
}
什么输入会产生错误?第二个函数的全部可以替换为
return b==biginger.ZERO?a:gcdEuclid(b,a.mod(b))代码>您正在从不应该到达的路径返回值,并使您的代码不必要地难以使用所有这些临时变量。那么,您是否在调试器中逐步完成了代码?