luogu P1009 阶乘之和 高精度

题目链接:https://www.luogu.org/problemnew/show/P1009
题目大意:求 S = 1 ! + 2 ! + . . . + n ! S=1!+2!+...+n! S=1!+2!+...+n!


#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 10;
int a[maxn],an[maxn],bn[maxn];
int n;

string fac(int n){
	if(n == 0) return "1";
	memset(a, 0, sizeof a);
	int tmp = n, len = 0;
	while(tmp) a[len++] = tmp % 10, tmp /= 10;   //将n放进数组中

	for(int i = n-1; i >= 2; i--){
		int c = 0;  //进位
		for(int j = 0;j < len; j++) a[j] = a[j] * i + c, c = a[j] / 10, a[j] %= 10;
		while(c) a[len++] = c % 10, c /= 10;
	}
	string res="";
	for(int i = 0; i < len; i++)
		res+=a[len-i-1] +'0';
	return res;
}
string add(string a,string b){
	memset(an, 0, sizeof an),memset(bn, 0,sizeof bn);
	int lena = a.length(),lenb = b.length();
	for(int i = 0;i < lena; i++) an[lena-i-1] = a[i] - '0';
	for(int i = 0;i < lenb; i++) bn[lenb-i-1] = b[i] - '0';
	int len = max(lena,lenb);
	for(int i = 0;i < len; i++){
		an[i]+=bn[i]; an[i+1] +=an[i]/10; an[i] %= 10;
	}
	if(an[len]) len++;
	string res="";
	for(int i=0;i<len;i++){
		res+=an[len-1-i]+'0';
	}
	return res;
}
int main()
{
	string res="0";
	cin>>n;
	while(n){
		res=add(res,fac(n));
		n--;
	}
	cout<<res<<endl;
	return 0;
}
### 关于洛谷 P1009 阶乘之和的题目解析 #### 题目描述 该题目要求计给定范围内所有自然数阶乘的总。具体来说,对于每一个不大于指定数值 \( N \),需要累加从 1 到 \( N \) 的各个数字对应的阶乘值。 #### 输入输出格式 - **输入**: 单个正整数 \( N \)(\( 1 ≤ N ≤ 50 \)) - **输出**: 所有小于等于 \( N \) 自然数的阶乘之和 #### 示例 当输入为 `3` 时,程序应返回的结果是 `9`,因为 \( 1! + 2! + 3! = 1 + 2 + 6 = 9 \)[^3]。 #### 解决方案概述 为了高效解决这个问题,可以采用迭代方法来逐项增加当前累积的阶乘结果,并将其加入到总的求变量中去。考虑到 Python 中的大整数支持特性,在处理较大范围内的阶乘时不会遇到溢出问题。 ```python def factorial_sum(n): sum_of_factorials, current_factorial = 0, 1 for i in range(1, n + 1): current_factorial *= i sum_of_factorials += current_factorial return sum_of_factorials if __name__ == "__main__": n = int(input()) result = factorial_sum(n) print(result) ``` 此代码片段定义了一个名为 `factorial_sum` 函数用于接收参数 `n` 并返回前 `n` 个自然数的阶乘之和。通过循环遍历从 1 至 `n` 的每个整数并不断更新两个局部变量:一个是用来存储当前正在计的那个数的阶乘 (`current_factorial`);另一个则是用来保存最终所需的阶乘之和(`sum_of_factorials`). 最后打印出所得到的结果.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值