用Python编程实现1!+2!+3!+...+n!
时间: 2023-11-25 21:05:40 浏览: 197
以下是Python编程实现1!+2!+3!+...+n!的方法:
```python
def factorial_sum(n):
sum = 0
factorial = 1
for i in range(1, n+1):
factorial *= i
sum += factorial
return sum
n = 5
print(factorial_sum(n)) # 输出:153
```
相关问题
用Python编程实现计算1+2!+3!+...+20!的和
以下是两种Python编程实现计算1+2!+3!+...+20!的和的方法:
方法一:
```python
n = 20
sum = 0
factorial = 1
for i in range(1, n+1):
factorial *= i
sum += factorial
print(sum)
```
方法二:
```python
def fact(i):
if i == 0:
return 1
else:
return i * fact(i-1)
n = 20
sum = 0
for i in range(1, n+1):
sum += fact(i)
print(sum)
```
编程计算1!+2!+3!+...+10!【要求:1. 首先定义阶乘计算函数,然后定义求和函数;2. 结果使用format输出1!+2!+3!+...+10!=4037913】
以下是Python代码实现:
```python
def fact(n):
"""计算n的阶乘"""
result = 1
for i in range(2, n+1):
result *= i
return result
def sum_fact(n):
"""计算1!+2!+3!+...+n!"""
sum = 0
for i in range(1, n+1):
sum += fact(i)
return sum
result = sum_fact(10)
print("1!+2!+3!+...+10!={}".format(result))
```
输出结果为:1!+2!+3!+...+10!=4037913
阅读全文