P1009 [NOIP1998 普及组] 阶乘之和 Java篇
题目描述
用高精度计算出 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。
思路
这题对于java来说可以用大数来解决。
java中用于操作大数的类主要有两个。
一个是BigInteger,代表大整数类用于对大整数进行操作。
另一个是BigDecimal,代表大浮点型。
如果不懂的可以看这篇文章
废话不多说直接上代码
import java.math.BigInteger; // 导入 java.math.BigInteger 类
import java.util.Scanner; // 导入 java.util.Scanner 类
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // 创建 Scanner 对象,从标准输入流读取数据
int n = in.nextInt(); // 读取一个整数 n
BigInteger a = BigInteger.valueOf(1L); // 创建 BigInteger 对象 a 并将其初始化为 1
BigInteger S = BigInteger.valueOf(0); // 创建 BigInteger 对象 S 并将其初始化为 0
BigInteger i = BigInteger.valueOf(1); // 创建 BigInteger 对象 i 并将其初始化为 1
BigInteger b = BigInteger.valueOf(1); // 创建 BigInteger 对象 b 并将其初始化为 1
while (n != 0){ // 当 n 不为 0 时执行循环
//求阶乘
a = a.multiply(i); // a *= i,计算 a 的值
//阶乘和
S = S.add(a); // S += a,计算 S 的值
//i++
i = i.add(b); // i += b,计算 i 的值
n--; // n 减 1
}
System.out.println(S); // 输出 S 的值
}
}
总结
知道大数计算就可以很快做出来。