我编写了在两个数字之间获取GCD(最大公共分区)的代码。因为我应该在第19位输入数字,我想我需要使用BigInteger数学类。但是,在编译代码后,会出现以下错误。
线程“主”java.lang.ArithmeticException中的例外: BigInteger:在test.GCD(test.java:9)、test.main(test.java:22)的test.GCD(test.java:9)处模不正
这是我的密码。
import java.util.*;
import java.math.BigInteger;
public class test {
public static BigInteger GCD(BigInteger a, BigInteger b) {
if (b.equals(0))
return a;
else
return GCD(b, a.mod(b));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger p = BigInteger.valueOf(1);
BigInteger q = BigInteger.valueOf(1);
BigInteger i = BigInteger.ONE;
BigInteger z = BigInteger.ONE;
p = sc.nextBigInteger();
q = sc.nextBigInteger();
while (true) {
if (GCD(p, q).compareTo(i) == -1) {
System.out.print("1");
}
else if(GCD(p, q).compareTo(i) == 0) {
System.out.print("1");
}
else if(GCD(p,q).compareTo(i) == 1) {
break;
}
i.add(z);
}
}
}没有语法错误。
发布于 2016-01-30 17:26:39
问题在于基本语句
if (b.equals(0))它试图将BigInteger b与明显不相等的装箱整数0进行比较,从而导致0作为模数被致命地传递。你可以用
if (b.equals(BigInteger.ZERO)) {https://stackoverflow.com/questions/35104671
复制相似问题