java - 处理100!在 Java/Groovy 中

标签 java groovy biginteger

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

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

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

最佳答案

只需将 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

关于java - 处理100!在 Java/Groovy 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25713464/

相关文章:

html - 为什么我的 CSS 样式表不能在 Grails 中链接?

android - 如何使用产品 flavor 和 APK 拆分从 Gradle 重命名和生成所有 APK 和 Bundle

java - BigInteger 分成几部分

java - 如何通过Lotus Notes java代理重定向网页?

java - Google App Engine - 了解部署模式下的 URL 与本地 - 导致登录问题

java - java对象转json

java - 无限循环。 Java 大整数

java 关于 Thread.interrupted() 的困惑

java - 从 linux 上的 groovy 脚本运行 java 可执行文件

php - PHP 中有 BigInteger 类吗?