You are on page 1of 6

REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 5

Experiment 5
Design and Analysis of Algorithms Lab
20CP209P

AIM: Implement matrix multiplication divide and conquer algorithm.

THEORY:
We take 2 nxn matrices as input and pad them with zero columns and zero rows such that the
resultant matrices’ size is a power of 2. Then in the recursive function, we recursively divide
both the matrices into 4 equal sized square matrices until they become unit matrices. Then we
multiply those unit matrices and then come out of all the recursive calls by adding the
particular sub-matrices of both the input matrices until we reach a resultant matrix of size n.

ALGORITHM:

CODE:
import math

1
REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 5

def m_mult(a,b,n):
if n==1:
r=[[a[0][0]*b[0][0]]]
return(r)
a1=a[:n//2]
a2=a[n//2:]
b1=b[:n//2]
b2=b[n//2:]
a11=[]
a12=[]
a21=[]
a22=[]
b11=[]
b12=[]
b21=[]
b22=[]
for i in a1:
a11.append(i[:n//2])
a12.append(i[n//2:])
for i in a2:
a21.append(i[:n//2])
a22.append(i[n//2:])
for i in b1:
b11.append(i[:n//2])
b12.append(i[n//2:])
for i in b2:
b21.append(i[:n//2])
b22.append(i[n//2:])
r1=m_mult(a11,b11,n//2)
r2=m_mult(a12,b21,n//2)

2
REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 5

r3=m_mult(a11,b12,n//2)
r4=m_mult(a12,b22,n//2)
r5=m_mult(a21,b11,n//2)
r6=m_mult(a22,b21,n//2)
r7=m_mult(a21,b12,n//2)
r8=m_mult(a22,b22,n//2)
c11=[]
c12=[]
c21=[]
c22=[]
for i in range(n//2):
ca=[]
cb=[]
cc=[]
cd=[]
for j in range(n//2):
ca.append(r1[i][j]+r2[i][j])
cb.append(r3[i][j]+r4[i][j])
cc.append(r5[i][j]+r6[i][j])
cd.append(r7[i][j]+r8[i][j])
c11.append(ca)
c12.append(cb)
c21.append(cc)
c22.append(cd)
c1=[]
c2=[]
for i in range(n//2):
c1.append(c11[i]+c12[i])
c2.append(c21[i]+c22[i])
c=c1+c2

3
REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 5

return(c)
n=int(input("enter size of matrices to be multiplied: "))
a=[]
for i in range(n):
ai=[]
for j in range(n):
ai.append(int(input("enter element of a: ")))
a.append(ai)
b=[]
for i in range(n):
bi=[]
for j in range(n):
bi.append(int(input("enter element of b: ")))
b.append(bi)
n1=math.ceil(math.log2(n))
n1=2**n1
for i in range(n):
a[i]+=[0]*(n1-n)
b[i]+=[0]*(n1-n)
for i in range(n,n1,1):
a.append([0]*n1)
b.append([0]*n1)
c=m_mult(a,b,n1)
print("MATRIX A:")
for i in range(n):
for j in range(n):
print(a[i][j],end=" ")
print()
print("MATRIX B: ")
for i in range(n):

4
REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 5

for j in range(n):
print(b[i][j],end=" ")
print()
print("MATRIX C=A*B: ")
for i in range(n):
for j in range(n):
print(c[i][j],end=" ")
print()

OUTPUT:

5
REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 5

ANALYSIS:
T(n) = 8T(n/2) + O(n^2)
Applying Master’s Theorem:
n^(logba) = n^(log28) = n^3
O(n^3) > O(n^2)
Therefore, this is Case-I of Master’s Theorem
So, T(n) = O(n^3)

You might also like