递归调用矩阵乘法实现斐波那契数列
时间: 2023-11-20 13:50:02 浏览: 108
Java递归实现斐波那契数列
可以使用矩阵乘法的递归调用来实现斐波那契数列,具体实现如下:
```python
def fib(n):
if n == 0 or n == 1:
return n
else:
F = [[1, 1], [1, 0]]
return matrix_pow(F, n-1)[0][0]
def matrix_mul(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 matrix_pow(F, n):
if n == 1:
return F
elif n % 2 == 0:
F_half = matrix_pow(F, n//2)
return matrix_mul(F_half, F_half)
else:
F_half = matrix_pow(F, (n-1)//2)
return matrix_mul(matrix_mul(F_half, F_half), F)
```
阅读全文