我正在尝试使用 BigInteger 制作扩展的欧几里得算法。但我不断收到错误消息
线程“主”java.lang.ArithmeticException 中的异常:BigInteger 除以零
我在谷歌上搜索,它说我可能会因为非整数除法而出错
我应该如何解决这个问题?
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 };
}
}