Skip to content

Commit

Permalink
Fibonacci using Recursive Matrix Multiplcation
Browse files Browse the repository at this point in the history
Python implementation of Nth fibonacci number using recursive matrix multiplication.
Time Complexity : O(lnN)
  • Loading branch information
detel committed Jun 27, 2015
1 parent 9f44b64 commit 1068ff3
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Fibonacci(Matrix).py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
def fib(n):
F = [[1,1],[1,0]]
if n == 0:
return 0

power(F,n-1)
return F[0][0]

def power(F,n):
if n == 0 or n == 1:
return

M = [[1,1],[1,0]]
power(F,n/2)
multiply(F,F)

if n%2 != 0: multiply(F,M)

def multiply(F,M):

w = F[0][0]*M[0][0] + F[0][1]*M[1][0];
x = F[0][0]*M[0][1] + F[0][1]*M[1][1];
y = F[1][0]*M[0][0] + F[1][1]*M[1][0];
z = F[1][0]*M[0][1] + F[1][1]*M[1][1];

F[0][0] = w
F[0][1] = x
F[1][0] = y
F[1][1] = z

0 comments on commit 1068ff3

Please sign in to comment.