Powers of a matrix
Given a 2 by 2 matrix M of natural numbers, a natural number n and a natural number m, compute M^n.
To avoid overflows, compute every element of M^n \pmod m.
Input: Input consists of several cases, each with M_{1,1}, M_{1,2}, M_{2,1} and M_{2,2} in this order, followed by n and m. Assume that the elements of M are not larger than 500, 0 \leq n \leq 10^9, and 2 \leq m \leq 1000.
Output: For every case, print the elements of M^n \pmod m in two lines following the format of the sample. Print a line with 10 dashes -
after every matrix.
Similar to P29212 Modular exponentiation. Are we at risk of integer overflow or not?
The standard matrix multiplication algorithm should work, or even done by hand (i.e. without for
loops) since the matrices are just 2\times 2.
//Powers of a matrix
#include<iostream>
#include<vector>
using namespace std;
typedef vector<vector<int>> Matrix;
int m;
& operator << (ostream& out, const Matrix& a){
ostream<< a[0][0] << " " << a[0][1] << endl;
out << a[1][0] << " " << a[1][1] << endl;
out << "----------";
out return out;
}
operator*(const Matrix& a, const Matrix& b) {
Matrix (2, vector<int>(2, 0));
Matrix cfor (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
for (int k = 0; k < 2; ++k){
[i][j] += a[i][k] * b[k][j];
c}
return c;
}
operator%(const Matrix& a, int m){
Matrix (2,vector<int>(2,0));
Matrix cfor (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
[i][j] = a[i][j] % m;
creturn c;
}
(){
Matrix identity(2,vector<int>(2,0));
Matrix idfor (int i = 0; i < 2; ++i)
[i][i] = 1;
idreturn id;
}
(const Matrix& a, int n, int m){
Matrix powerif (n == 0) return identity();
= power(a, n/2, m);
Matrix c return (n%2==0) ? (c*c) % m : (a*c*c) % m;
}
int main(){
(2,vector<int>(2));
Matrix aint n;
while(cin >> a[0][0] >> a[0][1] >> a[1][0] >>a[1][1] >> n >> m){
<< power(a,n,m) << endl;
cout }
}