I'm trying to program a GCD algorithm and everything seems to be correct except the StackOverflowError. Here is the code:
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:
Exception in thread "main" java.lang.StackOverflowError
at Gcd.gcdNaive(Gcd.java:7)
at Gcd.gcdNaive(Gcd.java:19)
return b == BigInteger.ZERO ? a : gcdEuclid(b, a.mod(b));
You're returning values from paths that should never be reached, and making your code unnecessarily hard to follow with all these temporary variables. – Paul Griffiths May 2 at 20:48