Matrix Powers
InterviewTime limit1sMemory limit128 MB
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 .
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 . For example, modulo ,
so raising the matrix above to the power modulo yields the matrix on the right.
Input
The input consists of several datasets. The first line of each dataset contains three integers , , and separated by single spaces.
- : the size () of the matrix
- : the modulo base
- : the power to which the matrix is raised
The following lines each hold one row of the matrix as integers with , 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 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.