We can express python’s line
(cur, next) = (next, cur+next)
as a simple matrix multiplication :
Where
import numpy as np | |
import sys | |
sys.set_int_max_str_digits(0) | |
def matrix_power(A: np.matrix, n: int) -> np.matrix: | |
if n == 0: | |
return np.matrix( ((1,0),(0,1)), dtype=object ) | |
elif n%2 == 1: | |
return np.matmul(A, matrix_power(A, n-1)) | |
else: | |
root = matrix_power(A, n/2) | |
return np.matmul(root, root) | |
def fibo_matrix(n: int) -> int: | |
M = np.matrix( ((0, 1), (1,1)), dtype=object ) | |
return matrix_power(M,n)[0,1] | |
import numpy as np | |
import sys | |
sys.set_int_max_str_digits(0) | |
def matrix_power(A: np.matrix, n: int) -> np.matrix: | |
if n == 0: | |
return np.identity(2, dtype=object ) | |
elif n%2 == 1: | |
return A @ matrix_power(A, n-1) | |
else: | |
root = matrix_power(A, n/2) | |
return root @ root | |
def fibo_matrix(n: int) -> int: | |
M = np.matrix( ((0, 1), (1,1)), dtype=object ) | |
return matrix_power(M,n)[0,1] |
import numpy as np | |
import sys | |
sys.set_int_max_str_digits(0) | |
def fib(n: int) -> int: | |
M = np.matrix( ((0, 1), (1,1)), dtype=object ) | |
return (M ** n)[0,1] |