Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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)
share|improve this question
1  
What inputs produce the error? –  Bill May 2 at 18:10
    
The entirety of your second function can be replaced by 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
    
Well, have you stepped through the code in the debugger? –  OldProgrammer May 2 at 20:51

1 Answer 1

The solution for gcdNaive is:

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);
    }
}

The complete solution for gcdEuclid is

public static BigInteger gcdEuclid(BigInteger a, BigInteger b) {

    if(b == BigInteger.ZERO)
    {
        return a;
    }

    return gcdEuclid(b, a.mod(b));
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.