I am trying to make an extended euclidean algorithm with the BigInteger. but I am keeping getting the error that
Exception in thread "main" java.lang.ArithmeticException: BigInteger divide by zero
I searched on google and it says that I might get an error because of the noninteger division
How should I solve this problem?
public static void main(String[] args) throws Exception{
BigInteger ex1 = new BigInteger("9");
BigInteger ex2 = new BigInteger("13");
//if(eA.gcd(eB).equals(BigInteger.ONE))
// {
BigInteger[] val = gcd(ex1,ex2);
System.out.println(val[1]);
System.out.println(val[2]);
// }
}
// Returns a triple {d, a, b} such that d = a*p + b*q
static BigInteger[] gcd(BigInteger p, BigInteger q) {
if (p.equals(BigInteger.ZERO))
return new BigInteger[] { p, BigInteger.valueOf(1), BigInteger.valueOf(0) };
BigInteger[] vals = gcd(q, p.remainder(q));
BigInteger d = vals[0];
BigInteger a = vals[2];
BigInteger b = vals[1].subtract((p.divide(q)).multiply(vals[2]));
return new BigInteger[] { d, a, b };
}
}
BigInteger[] vals = gcd(q, p.remainder(q));becauseqeventually becomes 0. By checking the gcd identities you can verify that gcd(0, a) = abs(a). Your code computes the gcd(0, a) as 0, which is wrong.qmust have been zero, asremainderanddividemay complain. That might happen for an older p and q withp.remainder(q)being zero.p.divide(q)what makes you certain thatqis never 0?