洛谷题单3-P1009 [NOIP 1998 普及组] 阶乘之和-python-流程图重构

题目描述

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

其中 ! 表示阶乘,定义为 n ! = n × ( n − 1 ) × ( n − 2 ) × ⋯ × 1 n!=n\times (n-1)\times (n-2)\times \cdots \times 1 n!=n×(n−1)×(n−2)×⋯×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,表示计算结果。

输入输出样例

输入

复制代码
3

输出

复制代码
9

说明/提示

【数据范围】

对于 100 % 100 \% 100% 的数据, 1 ≤ n ≤ 50 1 \le n \le 50 1≤n≤50。

方式

代码

python 复制代码
class Solution:
    @staticmethod
    def oi_input():
        """从标准输入读取数据"""
        num = int(input())
        return num

    @staticmethod
    def oi_test():
        """提供测试数据"""
        return 3

    @staticmethod
    def solution(num):
        t, sum = 1, 0

        for i in range(1, num + 1):
            t *= i
            sum += t

        print(sum)

oi_input = Solution.oi_input
oi_test = Solution.oi_test
solution = Solution.solution

if __name__ == '__main__':
    num = oi_test()
    # num = oi_input()
    solution(num)

流程图

是 否 开始 初始化current_factorial=1, total_sum=0 循环控制 i=1 到 num current_factorial *= i total_sum += current_factorial 输出total_sum 结束

相关推荐
兵慌码乱4 小时前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei7 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi0013 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn14 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
JieE2121 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi002 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用