编程序求1!+2!+...+20!
时间: 2023-09-13 12:07:44 浏览: 71
python 求1+2!+3!+...+20!的和 (示例)
5星 · 资源好评率100%
可以使用循环结构和递归函数来实现。以下是两种不同的方法:
方法1:使用循环结构计算阶乘
```python
result = 1 # 初始化结果为1
for i in range(1, 21):
result *= i # 依次乘以1~20
print(i, '!=', result)
```
输出结果:
```
1 != 1
2 != 2
3 != 6
4 != 24
5 != 120
6 != 720
7 != 5040
8 != 40320
9 != 362880
10 != 3628800
11 != 39916800
12 != 479001600
13 != 6227020800
14 != 87178291200
15 != 1307674368000
16 != 20922789888000
17 != 355687428096000
18 != 6402373705728000
19 != 121645100408832000
20 != 2432902008176640000
```
方法2:使用递归函数计算阶乘
```python
def factorial(n):
if n == 1:
return 1 # 1的阶乘为1
else:
return n * factorial(n-1) # n的阶乘为n * (n-1)的阶乘
for i in range(1, 21):
print(i, '!=', factorial(i))
```
输出结果同样为:
```
1 != 1
2 != 2
3 != 6
4 != 24
5 != 120
6 != 720
7 != 5040
8 != 40320
9 != 362880
10 != 3628800
11 != 39916800
12 != 479001600
13 != 6227020800
14 != 87178291200
15 != 1307674368000
16 != 20922789888000
17 != 355687428096000
18 != 6402373705728000
19 != 121645100408832000
20 != 2432902008176640000
```
阅读全文