程序在命令行参数N中读取,并将N! = 1 * 2 * ... * N
打印到标准输出。
public class Factorial {
// return n!
// precondition: n >= 0 and n <= 20
public static long factorial(long n) {
if (n < 0) throw new RuntimeException("Underflow error in factorial");
else if (n > 20) throw new RuntimeException("Overflow error in factorial");
else if (n == 0) return 1;
else return n * factorial(n-1);
}
public static void main(String[] args) {
long N = Long.parseLong(args[0]);
System.out.println(factorial(N));
}
}
样本输入(N)和输出(阶乘(N)):
5 >>> 120
12 >>> 479001600
20 >>> 2432902008176640000
21 >>> java.lang.RuntimeException: Overflow error in factorial
言论:
- 如果 N> 20
会溢出很长时间- 需要使用扩展的精度算法来处理更大的阶乘
所以,我的问题是如何使用扩展的精度算术来处理此代码中更大的阶乘?Java 中是否有任何其他变量类型可以保存比变量 long 更大的值?
BigInteger
和 BigDecimal
分别用于准确存储非常大的整数和十进制数。您通常会看到它们在递归中使用。
您可以使用BigDecimal
或BigIntger
和Map
的组合来存储和有效地计算非常大的东西,如斐波那契数列,而不会减慢计算机的速度。
也许你应该阅读BigInteger和BigDecimal。在来这里之前,先尝试做一些研究通常是一个不错的选择。