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) `

-------------Problems Reply------------

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

}