分别用递归算法和非递归算法定义一个函数,输出斐波那契数列(1,1,2,3,5,8..........)的前n项的值,并在主函数中进行测试,输出执行结果。。
时间: 2024-05-13 20:20:20 浏览: 7
好的,我可以帮你回答这个问题。以下是递归算法和非递归算法的定义:
递归算法:
```python
def fibonacci_recursive(n):
if n <= 1:
return n
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
```
非递归算法:
```python
def fibonacci_iterative(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
fib = [0, 1]
for i in range(2, n+1):
fib.append(fib[i-1] + fib[i-2])
return fib[n]
```
在主函数中,我们可以测试这两个函数并输出结果:
```python
n = 10
print("The first", n, "terms of the Fibonacci sequence are:")
for i in range(1, n+1):
print(fibonacci_recursive(i), end=" ")
print()
print()
print("The first", n, "terms of the Fibonacci sequence are:")
for i in range(1, n+1):
print(fibonacci_iterative(i), end=" ")
```
输出结果:
```
The first 10 terms of the Fibonacci sequence are:
1 1 2 3 5 8 13 21 34 55
The first 10 terms of the Fibonacci sequence are:
1 1 2 3 5 8 13 21 34 55
```
希望这个答案能够满足你的要求。如果你有其他问题,可以继续问我。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)