Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static int findDeterminant(int arr[][]){
- int rows = arr.length;
- int cols = arr[0].length;
- // Base Condition
- if(rows == 2 && cols == 2){
- // We stop when rows = 2, and cols = 2
- // because to calculate the
- // determinant of a 2 by 2 matrix
- // it does not need to be broken further
- int det = (arr[0][0] * arr[1][1]) - (arr[0][1] * arr[1][0]);
- return det;
- }
- else{
- int det = 0;
- int co_factors[][] = new int[rows - 1][cols - 1];
- for(int j = 0; j < cols; j++){
- // The element is arr[0][j]
- // Calculating the co-factors of
- // arr[0][j]
- int c_i = 0;
- for(int row = 1; row < cols; row++){
- int c_j = 0;
- for(int col = 0; col < cols; col++){
- // The co-factors are present in those columns to which
- // the element arr[0][j] does not belong
- if(col != j){
- co_factors[c_i][c_j] = arr[row][col];
- c_j++;
- }
- }
- c_i++;
- }
- System.out.println("Co-factors of " + arr[0][j] + " are");
- display(co_factors);
- // For even indexed columns the co-factors have a + sign
- // For odd indexed columns the co-factors have a - sign
- if(j % 2 == 0){
- det += arr[0][j] * findDeterminant(co_factors);
- }
- else{
- det -= arr[0][j] * findDeterminant(co_factors);
- }
- }
- return det;
- }
- }
Add Comment
Please, Sign In to add comment