一个正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!。
思路:
使用递归计算阶乘
求和,可以直接求和,也可以用列表将阶乘结果保存起来,最后求和。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
print factorial(5)
def sum_of_factorial(n):
sum = 0
for i in range(1, n+1):
sum += factorial(i)
return sum
print sum_of_factorial(20)
def sum_of_factorial2(n):
if n == 1:
return 1
else:
return n*sum_of_factorial2(n-1)
res = []
for i in range(1, 21):
res.append(sum_of_factorial2(i))
print sum(res)
sum = 0
for i in range(1, 21):
sum += sum_of_factorial2(i)
print sum