P1009 [NOIP1998 普及组] 阶乘之和

文章描述了一个编程竞赛中的问题,要求计算1到n的阶乘和,其中n不超过50。解决方案是利用Java的BigInteger类处理大整数运算,避免int或long类型溢出。代码示例展示了如何通过双重循环计算阶乘和,并将结果存储在BigInteger对象中。
摘要由CSDN通过智能技术生成

[NOIP1998 普及组] 阶乘之和

题目描述

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

其中 ! 表示阶乘,定义为 n ! = n × ( n − 1 ) × ( n − 2 ) × ⋯ × 1 n!=n\times (n-1)\times (n-2)\times \cdots \times 1 n!=n×(n1)×(n2)××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 1n50

【其他说明】

注,《深入浅出基础篇》中使用本题作为例题,但是其数据范围只有 n ≤ 20 n \le 20 n20,使用书中的代码无法通过本题。

如果希望通过本题,请继续学习第八章高精度的知识。

代码

用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 ±*/ 要用对应的方法,而且,不是自增的,需要对象接收,只有返回结构是修改后的,原数据不会修改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小袁拒绝摆烂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值