-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulinverse.c
110 lines (104 loc) · 2.17 KB
/
mulinverse.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include<stdio.h>
#define N 4
int determinant(int mat[N][N],int n)
{
int d=0,f;
if(n==1)
return mat[0][0];
int temp[n][n];
int sign=1;
for(f=0;f<n;f++)
{
getcofactor(mat,temp,0,f,n);
d+=sign*mat[0][f]*determinant(temp,n-1);
sign=-sign;
}
return d;
}
void getcofactor(int mat[N][N],int temp[N][N],int p,int q,int n)
{
int i=0,j=0,row,col;
for(row=0;row<n;row++)
{
for(col=0;col<n;col++)
{
if(row!=p && col!=q)
{
temp[i][j++]=mat[row][col];
if(j==n-1)
{
j=0;
i++;
}
}
}
}
}
void adjoint(int A[N][N],int adj[N][N])
{
if (N == 1)
{
adj[0][0] = 1;
return;
}
int sign = 1, temp[N][N];
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
getcofactor(A, temp, i, j, N);
sign = ((i+j)%2==0)? 1: -1;
adj[j][i] = (sign)*(determinant(temp, N-1));
}
}
}
void display(int mat[N][N],int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",mat[i][j]);
}
printf("\n");
}
}
int main()
{
int i,j,n,mat[N][N],det;
int adj[N][N];
float inv[N][N],deter;
printf("enter the size of matrix\n");
scanf("%d",&n);
printf("enter the elemants of array\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&mat[i][j]);
}
}
det=determinant(mat,n);
deter=determinant(mat,n);
printf("Determinant of the matrix is : %d\n",det);
display(mat,n);
adjoint(mat,adj);
display(adj,n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
inv[i][j] = adj[i][j]/deter;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%.3f ",inv[i][j]);
}
printf("\n");
}
return 0;
}