【问题标题】:Handling 100! in Java / Groovy处理100!在 Java/Groovy 中
【发布时间】:2014-09-07 18:32:10
【问题描述】:

我知道BigInteger 是处理非常大的数字时使用的类。我写了一个计算阶乘的简单脚本。但是,它在输入 25 及以上时中断。

/**
*    Calculates the factorial of a given number
*/
BigInteger fact(long n){
     def fact = 1
     while(n > 0){
         fact *= n--
     }
     return fact
}  

处理大到 100 的数字的正确方法是什么!

【问题讨论】:

  • @SotiriosDelimanolis 我得到的答案是0 或一些负数
  • 溢出。似乎fact 被推断为long,而不是BigInteger

标签: java groovy biginteger


【解决方案1】:

只需将 fact 声明为带有 Groovy 的 G 后缀的 BigInteger:

BigInteger fact(long n){
     def fact = 1G
     while(n > 0){
         fact *= n--
     }
     return fact
}  

assert fact(30) == 265252859812191058636308480000000
assert fact(25) == 15511210043330985984000000
assert fact(100) == 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

【讨论】:

    【解决方案2】:

    你可以这样尝试:

    import static java.math.BigInteger.ONE
    
    static BigInteger fact(BigInteger num) {
        num.equals(ONE) ? ONE : num.multiply(fact(num.subtract(ONE)));
    }
    

    还可以在这里查看彼得给出的答案:When calculating the factorial of 100 (100!) with Java using integers I get 0

    【讨论】:

    • 请解释一下:)
    • @LittleChild:- 我发布的链接解释了为什么你得到一个零公关负数。我认为这是因为溢出,因为最可能的猜测是事实将它花费的时间而不是 BigInteger。
    • @LittleChild:- 您可以尝试将方法定义更改为BigInteger fact(BigInteger n){BigInteger fact(long n){ def fact = 1G 并检查结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 2011-03-18
    • 2021-03-27
    相关资源
    最近更新 更多