本题来自 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的结果,然后把这结果的每个数字相加即可。
我想,应该是要练习递归阶乘吧,但我觉得用循环也挺方便的啊,就是很讨厌递归函数,总记不住写法,唉……