问题描述
给定一个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次幂所对应的矩阵。相邻的数之间用一个空格隔开
样例输入
2 2
1 2
3 4
样例输出
7 10
15 22
第一想法是采用numpy的dot函数实现,带入测试数据,结果正确但是就是不通过,猜测是不能导入外部包。下面是第一次的代码及结果展示
import numpy as np
N,M=map(int,input().split())
a=[list(map(int,input().split())) for i in range(N)]
if M!=0:
b = a
for i in range(M - 1):
b = np.dot(b, a)
for i in range(N):
for j in range(N):
print(b[i][j], end=" ")
print()
elif M==0:
b=[1]*N
c=np.diag(b)
for i in range(N):
for j in range(N):
print(c[i][j], end=" ")
print()
所以只能用笨办法尝试一下
N,M=map(int,input().split())
p = [list(map(int, input().split())) for i in range(N)]
if M==0:
b=[0]*(N*N)
q = []
for i in range(N):
for j in range(N):
if j == 0:
q.append([])
q[i].append(b[i * N + j])
for i in range(N):
for j in range(N):
if i==j:
q[i][j]=1
for i in range(N):
for j in range(N):
print(q[i][j], end=" ")
print()
else:
q = p
for i in range(M - 1):
h = []
a = q
u = p
for i in range(N):
c = u[i][:]
for m in range(N):
b = []
for j in range(N):
b.append(a[j][m])
d = 0
for n in range(N):
d += b[n] * c[n]
h.append(d)
q = []
for i in range(N):
for j in range(N):
if j == 0:
q.append([])
q[i].append(h[i * N + j])
for i in range(N):
for j in range(N):
print(q[i][j], end=" ")
print()
成功!!!!!