- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathDeterminantOfMatrix.java
47 lines (45 loc) · 1.28 KB
/
DeterminantOfMatrix.java
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
packagecom.thealgorithms.maths;
/*
* @author Ojasva Jain
* Determinant of a Matrix Wikipedia link: https://en.wikipedia.org/wiki/Determinant
*/
publicfinalclassDeterminantOfMatrix {
privateDeterminantOfMatrix() {
}
/**
* Calculates the determinant of a given matrix.
*
* @param a the input matrix
* @param n the size of the matrix
* @return the determinant of the matrix
*/
staticintdeterminant(int[][] a, intn) {
intdet = 0;
intsign = 1;
intp = 0;
intq = 0;
if (n == 1) {
det = a[0][0];
} else {
int[][] b = newint[n - 1][n - 1];
for (intx = 0; x < n; x++) {
p = 0;
q = 0;
for (inti = 1; i < n; i++) {
for (intj = 0; j < n; j++) {
if (j != x) {
b[p][q++] = a[i][j];
if (q % (n - 1) == 0) {
p++;
q = 0;
}
}
}
}
det = det + a[0][x] * determinant(b, n - 1) * sign;
sign = -sign;
}
}
returndet;
}
}