Matrix Powers

Interview

Time limit1sMemory limit128 MB

Summary
Given a square matrix, a modulus, and an exponent, compute the matrix raised to that power with all entries kept modulo M.
Level

Medium4 of 10

Topics
Matrix, Divide and conquer, Math
Solved
No attempts yet

Problem

Write a program that raises an integer matrix to a given power, performing every operation with modulo arithmetic. That is, every entry obtained during the computation is kept as its remainder modulo MM.

When two matrices are multiplied, each entry of the product is the sum of the pairwise products of the corresponding row and column, taken modulo MM. For example, modulo 1717,

(1234)×(1234)=((1⋅1+2⋅3) mod 17(1⋅2+2⋅4) mod 17(3⋅1+4⋅3) mod 17(3⋅2+4⋅4) mod 17)=(710155)\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} \times \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} = \begin{pmatrix} (1\cdot1 + 2\cdot3) \bmod 17 & (1\cdot2 + 2\cdot4) \bmod 17 \\ (3\cdot1 + 4\cdot3) \bmod 17 & (3\cdot2 + 4\cdot4) \bmod 17 \end{pmatrix} = \begin{pmatrix} 7 & 10 \\ 15 & 5 \end{pmatrix}

so raising the matrix above to the power 22 modulo 1717 yields the matrix on the right.

Input

The input consists of several datasets. The first line of each dataset contains three integers NN, MM, and PP separated by single spaces.

  • 1≤N≤1001 \le N \le 100: the size (N×NN \times N) of the matrix
  • 1≤M≤320001 \le M \le 32000: the modulo base
  • 1≤P≤320001 \le P \le 32000: the power to which the matrix is raised

The following NN lines each hold one row of the matrix as NN integers ii with 0≤i<M0 \le i < M, separated by single spaces.

The input is terminated by a line containing three zeros (0 0 0), which must not be processed.

Output

For each dataset, output the NN rows of the resulting matrix. Print each row on its own line with the values separated by single spaces.

Separate the outputs of consecutive datasets with a single blank line. Do not print a blank line after the last dataset.

Examples3

  1. Example 1

    Input
    2 17 2
    1 2
    3 4
    0 0 0
    
    Expected output
    7 10
    15 5
    
  2. Example 2

    Input
    2 17 1
    1 2
    3 4
    0 0 0
    
    Expected output
    1 2
    3 4
    
  3. Example 3

    Input
    1 100 10
    2
    0 0 0
    
    Expected output
    24