p1009 阶乘之和
题目描述
用高精度计算出 S = 1! + 2! + 3! + …+ n!S=1!+2!+3!+⋯+n!(n≤50)。
其中“!”表示阶乘,例如: 5!=5×4×3×2×1。
输入格式
一个正整数 n。
输出格式
一个正整数 S,表示计算结果。
题解
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
static BigInteger b = new BigInteger("1");
static BigInteger sum = new BigInteger("0");
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BigInteger a = scan.nextBigInteger();
scan.close();
while(true) {
sum = sum.add(factorial(a));
if(a.equals(b)) { // a==1时退出循环
break;
}
a = a.subtract(b); // a=a-1
}
System.out.println(sum);
}
//递归实现
static BigInteger factorial(BigInteger a) {
if(a.equals(b)) { //当值为1时跳出递归
return b;
}
return a.multiply(factorial(a.subtract(b)));
}
}
本文介绍了一种使用Java的BigInteger类来实现高精度计算阶乘之和的方法。通过递归函数计算从1到n的阶乘并求和,适用于n最大为50的情况。代码实现了输入n值后输出S=1!+2!+...+n!的结果。
944

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



