计并实现四种求解斐波那契数列的算法,并用计时法测量算法的运行时间
时间: 2024-09-22 12:08:13 浏览: 48
斐波那契数列是一个经典的动态规划问题,通常有多种方法可以求解,这里列举四种常见的算法:
1. **递归**:最直观的方法,通过定义F(n) = F(n-1) + F(n-2),但效率低下,因为存在大量的重复计算。递归的时间复杂度大约是O(2^n)。
```python
def fib_recursive(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fib_recursive(n - 1) + fib_recursive(n - 2)
```
2. **迭代**:使用循环避免了递归带来的冗余,将计算保存在数组中,时间复杂度降为O(n)。
```python
def fib_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
```
3. **矩阵快速幂**:利用矩阵乘法的性质,可以在O(logn)时间内求出斐波那契数。这种方法适用于大整数计算。
```python
def matrix_multiply(a, b):
c = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
for k in range(2):
c[i][j] += a[i][k] * b[k][j]
return c
def fast_fib(n):
base_matrix = [[1, 1], [1, 0]]
if n == 0:
return 0
result = matrix_multiply(base_matrix, pow(base_matrix, n - 1))
return result[0][0]
```
4. **备忘录化递归**:使用一个缓存存储已计算的结果,避免重复计算,提高效率到O(n)。
```python
cache = {}
def memoized_fib(n):
if n in cache:
return cache[n]
if n <= 1:
return n
result = memoized_fib(n - 1) + memoized_fib(n - 2)
cache[n] = result
return result
```
为了测量这些算法的实际运行时间,你可以使用Python的`timeit`模块:
```python
import timeit
for name, func in {"递归": fib_recursive, "迭代": fib_iterative,
"矩阵快速幂": fast_fib, "备忘录化递归": memoized_fib}:
print(f"{name}运行时间:{timeit.timeit(lambda: func(30), number=1)}秒")
```
阅读全文
相关推荐
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.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)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)