【问题标题】:(Java) How to use extended precision arithmetic to handle bigger factorials?(Java) 如何使用扩展精度算术来处理更大的阶乘?
【发布时间】:2013-09-27 13:09:26
【问题描述】:

程序读入命令行参数 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。这是一个更大的整数。
  • 是的,BigInteger 用于保存整数数据,BigDecimal 类用于保存十进制数据。
  • 那么什么是扩展精度算术?它是“BigInteger”??

标签: java overflow precision factorial arithmetic-expressions


【解决方案1】:

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

您可以使用BigDecimalBigIntgerMap 的组合来存储和有效地计算像斐波那契数列这样的超大型事物,而不会降低计算机速度。

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

【讨论】:

    猜你喜欢
    • 2017-07-16
    • 2012-08-23
    • 2014-01-09
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 2011-09-26
    相关资源
    最近更新 更多