Finding the matrix power.
Here’s an example Java program that calculates the power of a matrix:
import java.util.Arrays; public class MatrixPower { public static int[][] matrixPower(int[][] matrix, int power) { int[][] result = new int[matrix.length][matrix[0].length]; // Initialize the result matrix with the identity matrix for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (i == j) result[i][j] = 1; else result[i][j] = 0; } } // Calculate the power of the matrix while (power > 0) { if (power % 2 == 1) { result = multiplyMatrices(result, matrix); } matrix = multiplyMatrices(matrix, matrix); power /= 2; } return result; } public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) { int rows1 = matrix1.length; int cols1 = matrix1[0].length; int cols2 = matrix2[0].length; int[][] result = new int[rows1][cols2]; for (int i = 0; i < rows1; i++) { for (int j = 0; j < cols2; j++) { for (int k = 0; k < cols1; k++) { result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } return result; } public static void main(String[] args) { int[][] matrix = { {1, 2}, {3, 4} }; int power = 3; int[][] result = matrixPower(matrix, power); System.out.println("Matrix raised to the power " + power + ":"); for (int[] row : result) { System.out.println(Arrays.toString(row)); } } }
In this program, the `matrixPower` method calculates the power of a matrix by repeatedly squaring the matrix and multiplying the result by itself. The `multiplyMatrices` method is used to multiply two matrices together.
The example matrix used in the `main` method is a 2×2 matrix, and the power is set to 3. The result is printed to the console. You can modify the values of the `matrix` and `power` variables to test the program with different inputs.
Note that this implementation assumes square matrices, and the power should be a non-negative integer.
No comments yet! You be the first to comment.