斐波那契数列算法实现
时间: 2024-01-14 22:21:45 浏览: 133
以下是两种斐波那契数列算法的实现:
1. 递归算法:
```python
def fibonacci_recursive(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
# 示例
print(fibonacci_recursive(5)) # 输出:5
```
2. 迭代算法:
```python
def fibonacci_iterative(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
a, b = 0, 1
for _ in range(2, n+1):
a, b = b, a + b
return b
# 示例
print(fibonacci_iterative(5)) # 输出:5
```
阅读全文