我想写一个程序来评估给定整数的阶乘.
以下基础知识我在java中编写了以下代码:
long fact(int num){
if(num == 1)
return 1;
else
return num*fact(num-1);
}
但后来我意识到,对于许多整数输入,结果可能不是所期望的,因此对于测试直接给出输入为100.
我怀疑是真的,因为我得到的结果是“0”(原因结果可能超出了长期范围).
所以,我只是好奇并渴望知道如何让我的程序适用于输入< = 150. 我很感激C编程语言或Java中的任何有效解决方案.
解决方法
BigInteger是你的班级.它可以存储看似任何大小的整数.
static BigInteger fact(BigInteger num) {
if (num.equals(BigInteger.ONE))
return BigInteger.ONE;
else
return num.multiply(fact(num.subtract(BigInteger.ONE)));
}