f(n)=f(n-1)+f(n-2)
f(n-1)=f(n-2)+f(n-3)
So write like a matrix operation, ignore f(n-3), we could get
[f(n),f(n-1)]^T = [[1,1],[1,0]]*[f(n-1),f(n-2)]^T
void multiply(int A[], int B[], int C[]) {
C[0] = A[0]*B[0] + A[1]*B[2];
C[1] = A[0]*B[1] + A[1]*B[3];
C[2] = A[2]*B[0] + A[3]*B[2];
C[3] = A[2]*B[1] + A[3]*B[3];
}
void power(int A[], int n, int C[]) {
if (n==1) {
memcpy(C, A, 4*sizeof(int));
return;
}
int tmp[4];
power(A, n>>1, C);
multiply(C, C, tmp);
if (n & 1 == 1)
multiply(tmp, A, C);
else
memcpy(C, tmp, 4*sizeof(int));
}
int f(int n) {
int A[4] = {1,1,1,0};
int result[4];
power(A, n, result);
return result[0];
}
再贴一版Pytorch代码:
import torch
def matrix_power(matrix, n):
"""计算矩阵的n次幂"""
result = torch.eye(matrix.size(0), dtype=torch.int64)
base = matrix.clone()
while n > 0:
if n % 2 == 1:
result = torch.mm(result, base)
base = torch.mm(base, base)
n //= 2
return result
def fibonacci(n):
"""使用矩阵幂计算第n个斐波那契数"""
if n == 0:
return 0
elif n == 1:
return 1
F = torch.tensor([[1, 1],
[1, 0]], dtype=torch.int64)
# 计算F^(n-1)
result = matrix_power(F, n-1)
# F(n)是矩阵第一行第一列的元素
return result[0, 0].item()
# 测试函数
print(fibonacci(4)) # 输出第10个斐波那契数