Skip to content

Commit e0022ab

Browse files
Merge pull request #589 from akali/master
add fibonacci matrix mult implementation O(log(N))
2 parents bb7e4ba + b553dd4 commit e0022ab

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

Python/fibonacci.py

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,42 @@ def Fibonacci(n):
1111
else:
1212
return Fibonacci(n-1)+Fibonacci(n-2)
1313

14-
print(Fibonacci(9))
15-
1614
#Fibonacci with Looping
17-
def FibonacciLoop(n):
18-
for i in range(9):
15+
def FibonacciLoop(n):
16+
if n == 1:
17+
return 0
18+
for i in range(1 + n):
1919
if i == 0:
20-
print(0)
21-
after = 1
20+
sums = after = 0
2221
elif i == 1:
23-
print(1)
24-
before = 1
22+
sums = before = 1
2523
else:
2624
sums = before + after
27-
print(sums)
2825
before = after
2926
after = sums
27+
return sums
3028

31-
print(FibonacciLoop(9))
29+
# Fibonacci with matrix multiplication
30+
# (f[1], f[2]) * P = (f[2], f[3])
31+
# (f[1], f[2]) * P^n = (f[n+1], f[n+2])
32+
# P = [[0, 1],
33+
# [1, 1]]
34+
def FibonacciBinPow(n):
35+
m = [[0, 1],[1, 1]]
36+
37+
def multiply(a, b):
38+
# basic 2x2 matrix multiplication
39+
return [[a[0][0]*b[0][0]+a[0][1]*b[1][0], a[0][0]*b[0][1]+a[0][1]*b[1][1]],[a[1][0]*b[0][0]+a[1][1]*b[1][0], a[1][0]*b[0][1]+a[1][1]*b[1][1]]]
40+
41+
def binpow(m, p):
42+
if p == 0:
43+
return [[1, 0], [0, 1]]
44+
if p % 2 == 0:
45+
c = binpow(m, p / 2)
46+
return multiply(c, c)
47+
return multiply(m, binpow(m, p - 1))
48+
49+
return binpow([[0, 1], [1, 1]], n-1)[1][0]
50+
51+
for i in range(1, 10):
52+
print(Fibonacci(i), FibonacciLoop(i), FibonacciBinPow(i))

0 commit comments

Comments
 (0)