转载:https://www.cnblogs.com/syhyfh/p/12500019.html
问题描述
给定一个N阶矩阵A,输出A的M次幂(M是非负整数)
例如:
A =
1 2
3 4
A的2次幂
7 10
15 22
例如:
A =
1 2
3 4
A的2次幂
7 10
15 22
输入格式
第一行是一个正整数N、M(1<=N<=30, 0<=M<=5),表示矩阵A的阶数和要求的幂数
接下来N行,每行N个绝对值不超过10的非负整数,描述矩阵A的值
接下来N行,每行N个绝对值不超过10的非负整数,描述矩阵A的值
输出格式
输出共N行,每行N个整数,表示A的M次幂所对应的矩阵。相邻的数之间用一个空格隔开
import java.util.*; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] arr = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = sc.nextInt(); } } if (m == 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) System.out.print(1 + " "); else System.out.print(0 + " "); } System.out.println(); } System.exit(0); } int[][] arr1 = arr; for (int i = 1; i < m; i++) { arr1 = multiply(arr, arr1); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(arr1[i][j] + " "); } System.out.println(); } } private static int[][] multiply(int[][] a, int[][] b) { int len = a.length; int[][] res = new int[len][len]; for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { for (int k = 0; k < len; k++) { res[i][j] += a[i][k] * b[k][j]; } } } return res; } }