Finding the determinant of a matrix.
Here’s an example Java program that calculates the determinant of a square matrix using the recursive approach known as cofactor expansion:
public class DeterminantCalculator { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int determinant = calculateDeterminant(matrix); System.out.println("Determinant: " + determinant); } public static int calculateDeterminant(int[][] matrix) { int n = matrix.length; if (n == 1) { return matrix[0][0]; } int determinant = 0; int sign = 1; for (int i = 0; i < n; i++) { int[][] submatrix = new int[n - 1][n - 1]; for (int j = 1; j < n; j++) { for (int k = 0, index = 0; k < n; k++) { if (k == i) { continue; } submatrix[j - 1][index] = matrix[j][k]; index++; } } determinant += sign * matrix[0][i] * calculateDeterminant(submatrix); sign = -sign; } return determinant; } }
In this example, we have a 3×3 matrix defined in the `main` method. The `calculateDeterminant` method is used to recursively calculate the determinant of the matrix. The algorithm performs cofactor expansion along the first row and calls itself recursively to calculate the determinants of the submatrices. The sign alternates between positive and negative for each term in the expansion. Finally, the calculated determinant is printed to the console.
No comments yet! You be the first to comment.