首页 > 编程语言 > 详细

Python练习题 047:Project Euler 020:阶乘结果各数字之和

时间:2016-11-19 23:30:40      阅读:257      评论:0      收藏:0      [点我收藏+]

本题来自 Project Euler 第20题:https://projecteuler.net/problem=20

‘‘‘
Project Euler: Problem 20: Factorial digit sum
n! means n × (n ? 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is
3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
Answer: 648
‘‘‘

n = 100
fac = 1  #初始化阶乘结果
while n >= 1:
    fac *= n
    n -= 1

# 提取出阶乘结果的每个数字,形成列表lst
lst = [int(i) for i in str(fac)]

res = 0  #初始化相加结果
for i in range(len(lst)):
    res += lst[i]
print(res)

这题也容易,让先算出阶乘100的结果,然后把这结果的每个数字相加即可。

我想,应该是要练习递归阶乘吧,但我觉得用循环也挺方便的啊,就是很讨厌递归函数,总记不住写法,唉……

Python练习题 047:Project Euler 020:阶乘结果各数字之和

原文:http://www.cnblogs.com/iderek/p/6081645.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!