与一位朋友就Java上的BigInteger类进行了一些测试,他制作了一个代码,打印“ n:”并接收给定的数字以查找其阶乘。一段时间后,我尝试计算1,000,000的阶乘,但随后(经过几分钟的计算),控制台仅显示了很多零,甚至没有打印“ n:”(运行程序时会打印)和“ n” !:“显示结果时。
在测试中,直到300k,代码都可以正常工作(微积分时间除外,但这在给定数字的情况下尚在期望中)。观察:循环用于分隔行,因为它们仅支持4096个字符
public static BigInteger zero = new BigInteger("0");
public static BigInteger one = new BigInteger("1");
public static BigInteger minusOne = new BigInteger("-1");
public static BigInteger fat(BigInteger n) {
if(n.equals(zero)) {
return new BigInteger("1");
}
BigInteger i = new BigInteger(n.toString());
while(!i.equals(one)) {
i = i.add(minusOne);
n = n.multiply(i);
}
return new BigInteger(n.toString());
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.print("n: ");
BigInteger bigInt = new BigInteger(in.nextLine());
String bigString = fat(bigInt).toString();
int strSize = bigString.length();
System.out.println("n! = ");
for (int i = 0; i < strSize; i++) {
if((i+1)%4096==0) {
System.out.printf("%c\n",bigString.charAt(i));
}else {
System.out.print(bigString.charAt(i));
}
}
in.close();
}
}
应该发生一些输出,但不是一堆零,并且显然会覆盖第一张纸。即使有大量数字(例如300k),打印件“ n:”和“ n !:”也停留在那里。没有关于溢出或堆栈溢出的错误消息。在某个时候,我认为控制台仅显示数字的最后一部分,但是问一个朋友,他说了有关控制台或Eclipse的一些未知错误(至少对我们而言)。