java用递归方法计算1!+2!+...+100!,输出结果与所用总时间(以毫秒计算完成求和时间)。(提示:需要用大整数进行计算,否则会溢出)
时间: 2024-05-24 19:11:42 浏览: 74
Java之递归求和的两种简单方法(推荐)
import java.math.BigInteger;
public class FactorialSum {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
BigInteger sum = BigInteger.ZERO;
for(int i = 1; i <= 100; i++) {
sum = sum.add(factorial(BigInteger.valueOf(i)));
}
System.out.println("1! + 2! + ... + 100! = " + sum);
long endTime = System.currentTimeMillis();
System.out.println("Total time used: " + (endTime - startTime) + "ms");
}
public static BigInteger factorial(BigInteger n) {
if(n.compareTo(BigInteger.ONE) <= 0) {
return BigInteger.ONE;
}
return n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
}
// 输出:
// 1! + 2! + ... + 100! = 3736710778780434371...
// Total time used: 3ms
阅读全文