处理100!在Java/Groovy中

处理100!在Java/Groovy中,java,groovy,biginteger,Java,Groovy,Biginteger,我知道biginger是处理非常大的数字时要使用的类。我写了一个简单的脚本来计算阶乘。但是,它在输入25及以上时中断 /** * Calculates the factorial of a given number */ BigInteger fact(long n){ def fact = 1 while(n > 0){ fact *= n-- } return fact } 处理大到100的数字的正确方法是什么?您可

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

/**
*    Calculates the factorial of a given number
*/
BigInteger fact(long n){
     def fact = 1
     while(n > 0){
         fact *= n--
     }
     return fact
}  
处理大到100的数字的正确方法是什么

您可以这样尝试:

import static java.math.BigInteger.ONE

static BigInteger fact(BigInteger num) {
    num.equals(ONE) ? ONE : num.multiply(fact(num.subtract(ONE)));
}
也请检查Peter给出的答案:

您可以这样尝试:

import static java.math.BigInteger.ONE

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

这里还要检查Peter给出的答案:

只需将
事实
声明为带有Groovy的
G
后缀的大整数:

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

只需将
fact
声明为带有Groovy的
G
后缀的大整数:

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

@我得到的答案是
0
或一些负数流。似乎
事实
被推断为
,而不是
大整数
@SotiriosDelimanolis我得到的答案是
0
或一些负数流。似乎
事实
被推断为
,而不是
大整数
。请解释:)@LittleChild:-我发布的链接解释了为什么你会得到零pr负数。我认为这是因为溢出,因为最有可能的猜测是事实将其作为long而不是biginger。@LittleChild:-您可以尝试将方法定义更改为
biginger事实(biginger n){
biginger事实(long n){def fact=1G
并检查结果。解释,请:)@LittleChild:-我发布的链接解释了为什么你会得到一个零pr负数。我认为这是因为溢出,因为最有可能的猜测是,这个事实花费的时间与BigInteger一样长。@LittleChild:-你可以尝试更改我的答案方法定义为
biginger事实(biginger n){
biginger事实(long n){def fact=1G
,并检查结果。