import java.math.BigInteger;
public class Factorial {
//2) 求1!+2!+……+20!
public static void main(String[] args){
BigInteger sum=BigInteger.ZERO;
for(BigInteger i=BigInteger.ONE;i.intValue()<=20;){
i=i.add(BigInteger.ONE);
sum=sum.add(factorial(i));
}
System.out.println(sum.toString());
}
public static BigInteger factorial(BigInteger bigInteger){
if(bigInteger.intValue()==1){
return BigInteger.ONE;
}
else
return bigInteger.multiply(factorial(bigInteger.subtract(BigInteger.ONE)));
}
}
结果:53652269665821260312
本文提供了一个使用Java实现的程序来计算从1到20的阶乘之和。通过递归调用的方法实现了阶乘的计算,并利用BigInteger确保了大数运算的准确性。
4276

被折叠的 条评论
为什么被折叠?



