[NOIP1998 普及组] 阶乘之和
题目描述
用高精度计算出 S = 1 ! + 2 ! + 3 ! + ⋯ + n ! S = 1! + 2! + 3! + \cdots + n! S=1!+2!+3!+⋯+n!( n ≤ 50 n \le 50 n≤50)。
其中 !
表示阶乘,定义为
n
!
=
n
×
(
n
−
1
)
×
(
n
−
2
)
×
⋯
×
1
n!=n\times (n-1)\times (n-2)\times \cdots \times 1
n!=n×(n−1)×(n−2)×⋯×1。例如,
5
!
=
5
×
4
×
3
×
2
×
1
=
120
5! = 5 \times 4 \times 3 \times 2 \times 1=120
5!=5×4×3×2×1=120。
输入格式
一个正整数 n n n。
输出格式
一个正整数 S S S,表示计算结果。
样例 #1
样例输入 #1
3
样例输出 #1
9
提示
【数据范围】
对于 100 % 100 \% 100% 的数据, 1 ≤ n ≤ 50 1 \le n \le 50 1≤n≤50。
【其他说明】
注,《深入浅出基础篇》中使用本题作为例题,但是其数据范围只有 n ≤ 20 n \le 20 n≤20,使用书中的代码无法通过本题。
如果希望通过本题,请继续学习第八章高精度的知识。
代码
用java的BigInteger可以轻松解决
import java.math.BigInteger;
import java.util.Scanner;
@SuppressWarnings("all")
public class Main{
public static void main(String [] args){
Scanner scanner = new Scanner(System.in);
int nextInt = scanner.nextInt();
BigInteger bigInteger = new BigInteger("0");
for(int i=1;i<=nextInt;i++) {//可能re也会超过int范围,正好也用BigInteger储存吧
BigInteger bigInteger2 = new BigInteger("1");
for(int j=1;j<=i;j++) {
bigInteger2=bigInteger2.multiply(BigInteger.valueOf(j));
}
bigInteger =bigInteger.add(bigInteger2);
}
System.out.println(bigInteger);
scanner.close();
}
}
注意:
1.阶乘的结果也要用BigInteger存储,因为可能超出Int和long范围
2.可以用BigInteger.valueOf(int 变量)来实现变量穿件BigInteger对象
3.注意BigInteger ±*/ 要用对应的方法,而且,不是自增的,需要对象接收,只有返回结构是修改后的,原数据不会修改