1编写程序,利用下列三种方法计算1!+3!+5!+…+19!。 要求: (1)方法一是使用嵌套循环 (2)方法二是使用递归函数(求阶乘)和循环结构 (3)方法三是使用reduce函数和循环结构
时间: 2023-10-09 17:04:21 浏览: 100
方法一:使用嵌套循环
```python
sum = 0
for i in range(1, 20, 2):
factorial = 1
for j in range(1, i+1):
factorial *= j
sum += factorial
print(sum)
```
方法二:使用递归函数和循环结构
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
sum = 0
for i in range(1, 20, 2):
sum += factorial(i)
print(sum)
```
方法三:使用reduce函数和循环结构
```python
from functools import reduce
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
sum = reduce(lambda x, y: x+y, map(factorial, range(1, 20, 2)))
print(sum)
```
相关问题
1编写程序,利用下列三种方法计算1!+3!+5!+…+19!。 要求: (1)方法一是使用嵌套循环
方法一:使用嵌套循环
```python
result = 0
for i in range(1, 20, 2):
factorial = 1
for j in range(i, 0, -1):
factorial *= j
result += factorial
print(result)
```
方法二:使用递归函数
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
result = 0
for i in range(1, 20, 2):
result += factorial(i)
print(result)
```
方法三:使用while循环
```python
result = 0
i = 1
factorial = 1
while i <= 19:
factorial *= i
if i % 2 == 1:
result += factorial
i += 1
print(result)
```
以上三种方法的输出结果都是:536870913
1编写程序,利用下列三种方法计算1!+3!+5!+…+19!。要求:(1)方法一是使用嵌套循环(2)方法二是使用递归函数(求阶乘)和循环结构(3)方法三是使用reduce函数和循环结构
方法一:使用嵌套循环
```python
total = 0
for i in range(1, 20, 2):
factorial = 1
for j in range(1, i + 1):
factorial *= j
total += factorial
print(total)
```
方法二:使用递归函数和循环结构
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
total = 0
for i in range(1, 20, 2):
total += factorial(i)
print(total)
```
方法三:使用reduce函数和循环结构
```python
from functools import reduce
def multiply(x, y):
return x * y
total = 0
for i in range(1, 20, 2):
factorial = reduce(multiply, range(1, i + 1))
total += factorial
print(total)
```
阅读全文