递推维护当前阶乘并累加,求 1! 到 n! 的和。
OJ: noi_openjudge
题目 ID: ch0105-34
难度:入门
标签:循环数学递推python
日期: 2026-07-30 23:01
题意
求
思路
不必每次从头计算阶乘。若 factorial 已经是 total 后继续下一轮即可。
代码
Python代码
python
limit = int(input())
factorial = 1
total = 0
for number in range(1, limit + 1):
factorial *= number
total += factorial
print(total)C++代码
cpp
#include <cstdio>
int main(){
int n;
scanf("%d",&n);
int sum=0,i,s = 1;
for (i=1;i<=n;i++){
s = s*i;
sum += s;
}
printf("%d\n",sum);
return 0;
}复杂度
时间复杂度为
总结
相邻阶乘只差一次乘法,维护递推值比重复计算更清晰也更高效。