P1009 [NOIP1998 Popularization Group] Factorial Sum (Java)

[NOIP1998 Popularization Group] Factorial Sum

Title description

Calculate with high precision S=1!+2!+3!+...+n! (n≤50).

Among them, "!" means factorial, for example: 5!=5×4×3×2×1.

Input format

A positive integer n.

Output format

A positive integer S indicates the calculation result.

Sample input and output

Input #1
3
Output #1
9
Description/Prompt
[Data Range]

For 100% of the data, 1≤n≤50.

Problem-solving ideas:

Java's large number class: BigInteger method

code show as below:

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);
	}
}

Guess you like

Origin blog.csdn.net/weixin_45894701/article/details/114951522