給定一個N階矩陣A,輸出A的M次冪(M是非負整數)(Java)


 
         
轉載:https://www.cnblogs.com/syhyfh/p/12500019.html
問題描述
 
         
  給定一個N階矩陣A,輸出A的M次冪(M是非負整數)
  例如:
  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個整數,表示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; } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM