题目描述:
用高精度计算出S=1!+2!+3!+...+n!(n≤50),其中"!"表示阶乘,例如:5!=5×4×3×2×1。
输入正整数n,输出计算结果S。
代码:
java
package lanqiao;
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
BigInteger sum = new BigInteger("0");
for(int i = 1;i <= n;i ++)
{
sum = sum.add(f(i));
}
System.out.println(sum);
}
public static BigInteger f(int n)
{
BigInteger sum = new BigInteger("1");
for(int i = 1;i <= n;i ++)
{
sum = sum.multiply(new BigInteger(String.valueOf(i)));
}
return sum;
}
}