P1009 [NOIP1998 普及组] 阶乘之和(Java)

[NOIP1998 普及组] 阶乘之和

题目描述

用高精度计算出S=1!+2!+3!+⋯+n!(n≤50)。

其中“!”表示阶乘,例如:5!=5×4×3×2×1。

输入格式

一个正整数 n。

输出格式

一个正整数 S,表示计算结果。

输入输出样例

输入 #1
3
输出 #1
9
说明/提示
【数据范围】

对于 100% 的数据,1≤n≤50。

解题思路:

Java的大数类:BigInteger方法

代码如下:

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    
    
	public static BigInteger jc(int n) {
    
      //计算阶乘
		BigInteger s = BigInteger.ONE;
		for (int i = 2; i <= n; i++)
			s = s.multiply(new BigInteger(Integer.toString(i)));
		return s;
	}
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		BigInteger ans = new BigInteger("0");
		for (int i = 1; i <= n; i++) {
    
    
			ans = ans.add(jc(i));  //阶乘和累加
		}
		System.out.println(ans);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_45894701/article/details/114951522