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