I have this weird kind of error.
I am trying implement basic Euclidean algorithm using the BigInteger class as shown. When i run it, it throws StackoverFlowError, while if i debug it, it runs through correctly and gives me the correct answer.
I seriously dont understand the difference during debug and normal run.
static BigInteger gcd(BigInteger a, BigInteger b) {
if (a.equals(BigInteger.ZERO)) {
return b;
} else if (b.equals(BigInteger.ZERO)) {
return a;
}
BigInteger max = a.max(b);
BigInteger min = a.min(b);
return gcd(max.subtract(min), min);
}
This is not the Euclidean algorithm for GCD. The correct GCD algorithm can be easily stated as a recursive procedure because the number of iterations is in practice small. But this incorrectly implemented algorithm can run for millions of iterations, e.g. if ‘a’ is 1,000,000 and ‘b’ is 1, which results in one million recursive calls.
(However, the call is a tail recursive call so a good Java implementation would actually optimize away the stack frame. However, it seems this does not happen here. Although for some unknown reason the debugger version could implement tail call optimization, though that sounds odd.)
In the actual algorithm, the recursive step is (a % b, b) instead of (a – b, b). Google for “euclid GCD algorithm”.