Description
给定一个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
Input
第一行是一个正整数N、M(1<=N<=30, 0<=M<=5),表示矩阵A的阶数和要求的幂数
接下来N行,每行N个绝对值不超过10的非负整数,描述矩阵A的值
接下来N行,每行N个绝对值不超过10的非负整数,描述矩阵A的值
Output
输出共N行,每行N个整数,表示A的M次幂所对应的矩阵。相邻的数之间用一个空格隔开
Sample Input
2 2 1 2 3 4
Sample Output
7 10 15 22
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int i,j,k;
long [][]a=new long[n][n];
long [][]b=new long[n][n];
long [][]c=new long[n][n];
for(i=0;i<n;i++)
for(j=0;j<n;j++){
a[i][j]=b[i][j]=sc.nextLong();
c[i][j]=0;
}
for(k=1;k<m;k++){
for(i=0;i<n;i++)
for(j=0;j<n;j++){
c[i][j]=0;
for(int z=0;z<n;z++)
c[i][j]+=b[i][z]*a[z][j];
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
b[i][j]=c[i][j];
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(m==0){
if(i==j) System.out.print("1 ");
else System.out.print("0 ");
}
else if(m==1){
System.out.print(a[i][j]+" ");
}
else{
System.out.print(c[i][j]+" ");
}
}
System.out.println();
}
}
}