洛谷P1009 [NOIP1998 普及组] 阶乘之和
题目描述
用高精度计算出 S = 1!+2!+3!+⋯+n!(0n≤50)。
其中“!”表示阶乘,例如:5!=5×4×3×2×1。
分析
由于n 的范围在0~50之间,所以当n太大时,int类型表示的范围就会无法达到要求,变为负数,所以在java中表示大数的话,可以用BigInteger类。
Java代码
import java.io.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
// 求给定数字n的阶乘并返回BigInteger类型的变量值
public static BigInteger fac(int n) {
BigInteger big = new BigInteger("1");
BigInteger num = new BigInteger("1");
for(int i = 0; i < n; i++) {
big = big.multiply(num);
num = num.add(new BigInteger("1"));
}
return big;
}
public static void main(String args[]) throws Exception {
Scanner cin=new Scanner(System.in);
BigInteger big = new BigInteger("0");
int cnt = 1;
int sum = 0;
int n = cin.nextInt();
for(int i = 1; i <= n; i++) {
big = big.add(fac(i));
}
System.out.println(big);
}
}