File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package Maths ;
2+ import java .util .*;
3+
4+ /*
5+ * @author Ojasva Jain
6+ * Determinant of Matrix Wikipedia link : https://en.wikipedia.org/wiki/Determinant
7+ */
8+ public class DeterminantOfMatrix
9+ {
10+ // Determinant calculator
11+ //@return determinant of the input matrix
12+ static int determinant (int a [][], int n )
13+ {
14+ int det = 0 , sign = 1 , p = 0 , q = 0 ;
15+ if (n ==1 )
16+ {
17+ det = a [0 ][0 ];
18+ }
19+ else
20+ {
21+ int b [][] = new int [n -1 ][n -1 ];
22+ for (int x = 0 ; x < n ; x ++)
23+ {
24+ p =0 ;q =0 ;
25+ for (int i = 1 ;i < n ; i ++)
26+ {
27+ for (int j = 0 ; j < n ;j ++)
28+ {
29+ if (j != x )
30+ {
31+ b [p ][q ++] = a [i ][j ];
32+ if (q % (n -1 ) == 0 )
33+ {
34+ p ++;
35+ q =0 ;
36+ }
37+ }
38+ }
39+ }
40+ det = det + a [0 ][x ] *determinant (b , n -1 ) * sign ;
41+ sign = -sign ;
42+ }
43+ }
44+ return det ;
45+ }
46+ //Driver Method
47+ public static void main (String [] args ){
48+ Scanner in = new Scanner (System .in );
49+ //Input Matrix
50+ System .out .println ("Enter matrix size (Square matrix only)" );
51+ int n = in .nextInt ();
52+ System .out .println ("Enter matrix" );
53+ int a [][] = new int [n ][n ];
54+ for (int i =0 ;i <n ;i ++){
55+ for (int j =0 ;j <n ;j ++){
56+ a [i ][j ] = in .nextInt ();
57+ }
58+ }
59+ System .out .println (determinant (a , n ));
60+ }
61+ }
You can’t perform that action at this time.
0 commit comments