Skip to content

Commit 6ae620f

Browse files
authored
Merge pull request #715 from ShivangiBhatnagar-246/StrassenAlgoinC
Strassen's Algo Matrix Multiplication in C
2 parents e666ca5 + 39a73c2 commit 6ae620f

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Arrays/Strassen's_Algo.c

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// Problem Description: Strassens Algorithm in C Language for Matrix Multiplication
2+
#include<stdio.h>
3+
int main(){
4+
int mat1[2][2], mat2[2][2], mat3[2][2], i, j;
5+
int a, b, c, d , e, f, g;
6+
7+
printf("Enter the elements of first matrix:\n"); //Input elements for matrix 1
8+
for(i = 0;i < 2; i++)
9+
{
10+
for(j = 0;j < 2; j++)
11+
{
12+
scanf("%d", &mat1[i][j]);
13+
}
14+
}
15+
16+
printf("Enter the elements of second matrix:\n"); // Input elements for matrix 2
17+
for(i = 0; i < 2; i++)
18+
{
19+
for(j = 0;j < 2; j++)
20+
{
21+
scanf("%d", &mat2[i][j]);
22+
}
23+
}
24+
//Displaying
25+
printf("The Matrix 1:\n"); //Displaying matrix 1 elements
26+
for(i = 0; i < 2; i++)
27+
{
28+
for(j = 0; j < 2; j++)
29+
{
30+
printf("%d\t", mat1[i][j]);
31+
}
32+
printf("\n");
33+
}
34+
35+
printf("The Matrix 2:\n"); //Displayimg matrix 2 elements
36+
for(i = 0;i < 2; i++)
37+
{
38+
for(j = 0;j < 2; j++)
39+
{
40+
printf("%d \t", mat2[i][j]);
41+
}
42+
printf("\n");
43+
}
44+
45+
//reduced eight times Time Complexity to Seven Times i.e T(N) = 7T(N/2) + O(N^2)
46+
47+
// Compexity: before O(n^3) when used Standard Matrix Multiplication , now :O(n^2.808) when used Strassen's Algorithm
48+
49+
//Now we can calculate the product of mat1[i][j] and mat2[i][j] with the following formulas:
50+
a= (mat1[0][0] + mat1[1][1]) * (mat2[0][0] + mat2[1][1]);
51+
b= (mat1[1][0] + mat1[1][1]) * mat2[0][0];
52+
c= mat1[0][0] * (mat2[0][1] - mat2[1][1]);
53+
d= mat1[1][1] * (mat2[1][0] - mat2[0][0]);
54+
e= (mat1[0][0] + mat1[0][1]) * mat2[1][1];
55+
f= (mat1[1][0] - mat1[0][0]) * (mat2[0][0]+mat2[0][1]);
56+
g= (mat1[0][1] - mat1[1][1]) * (mat2[1][0]+mat2[1][1]);
57+
//Now with a,b,c,d,e,f,g which are the submatrices of size N/2*N/2
58+
59+
//Calculate the elements of matrix 3, The resultant matrix mat3[i][j]
60+
mat3[0][0] = a + d- e + g;
61+
mat3[0][1] = c + e;
62+
mat3[1][0] = b + d;
63+
mat3[1][1] = a - b + c + f;
64+
65+
printf("Strassen's algorithm : Matrix Multiplication\n"); //Resultant matrix after applying Strassen's Algo
66+
for(i = 0; i < 2 ; i++)
67+
{
68+
for(j = 0;j < 2; j++)
69+
{
70+
printf("%d\t", mat3[i][j]); //displaying resultant matrix
71+
}
72+
printf("\n");
73+
}
74+
return 0;
75+
}

0 commit comments

Comments
 (0)