A matrix to a power

Repeated multiplication by the same matrix can describe a process that runs many times, such as the Fibonacci numbers.

What to build

Compute Aᵏ for a square matrix A and a whole number k.

Requirements

  • Read n, k and the n × n matrix A.
  • Aᵏ is A multiplied by itself k times; A⁰ is the identity matrix.
  • Print the rows of the result with entries separated by single spaces.

Input

Line 1: n (1 to 4) and k (0 to 40). Then n lines of n whole numbers.

Output

The n rows of Aᵏ, entries separated by single spaces.

Constraints

Entries are between -3 and 3. Results fit easily in Python integers.

Example

Input:

2 5
1 1
1 0

Output:

8 5
5 3

Why it works

Matrix multiplication is associative, so Aᵏ is well defined. For A = [[1, 1], [1, 0]] the power Aᵏ contains Fibonacci numbers, so a matrix power computes them by multiplication alone.

Examples

Example 1 · Input
2 5
1 1
1 0
Expected output
8 5
5 3
Example 2 · Input
2 0
3 1
2 5
Expected output
1 0
0 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Start from the identity matrix and multiply by A exactly k times.

Hint 2

Python integers do not overflow, so the results are exact.

Hint 3

The tests use small matrices and k up to 40; it is fine to multiply k times.

Solution

Show one correct solution (try it yourself first)
n, k = [int(x) for x in input().split()]
A = [[int(x) for x in input().split()] for _ in range(n)]

def matmul(X, Y):
    return [[sum(X[i][t] * Y[t][j] for t in range(n)) for j in range(n)] for i in range(n)]

result = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
for _ in range(k):
    result = matmul(result, A)
for row in result:
    print(*row)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Matrices and matrix multiplication →