I have 2 functions to get the n-th fibonacci number. The 1st one uses recursive calls to calculate the power(M, n), while the 2nd function uses iterative approach for power(M, n). Theoretically (at least what I think), they should have the same speed O(log n), but why when I run both, the 2nd one is much slower than the 1st one?
def fib_1(n):
from numpy import matrix
def power(F, n):
if n == 0 or n == 1: return matrix('1 1; 1 0', object)
F = power(F, n >> 1) # n // 2
F = F * F
if n % 2 == 0:
return F
if n % 2 != 0:
return F * matrix('1 1; 1 0', object)
F = matrix('1 1; 1 0', object)
F = power(F, abs(n)-1)
return F[0,0] if n > 0 else int((-1)**(n+1)) * F[0,0]
def fib_2(n):
from numpy import matrix
def power(F, n):
M = matrix('1 1; 1 0', object)
while n > 0:
if n & 1 == 1:
M = F * M
n = n >> 1 # n = n // 2
F = F * F
return M
F = matrix('1 1; 1 0', object)
F = power(F, abs(n)-2)
return F[0,0] if n > 0 else int((-1)**(n+1)) * F[0,0]
fib_2
is much faster. \$\endgroup\$