(Java)如何使用扩展精度算法来处理更大的阶乘?

时间:2013-09-22 15:48:15

标签: java overflow precision factorial arithmetic-expressions

程序读入命令行参数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更大的值?

1 个答案:

答案 0 :(得分:1)

BigIntegerBigDecimal可用于分别准确存储非常大的整数和十进制数。您通常会在递归中看到它们。

您可以使用BigDecimalBigIntgerMap的组合来存储和有效地计算像Fibonacci序列这样的非常大的内容,而不会让您的计算机减速到爬行。

也许你应该阅读BigInteger and BigDecimal。在来到这里之前先尝试做一些研究通常是一个不错的选择。