Operators make maths code read like maths. Build a matrix type and raise it to a power.
What to build
A Matrix class for 2 × 2 matrices with addition, multiplication and printing.
Requirements
- Write
operator+andoperator*as const members that return a new matrix. - Write
operator<<to print[a b; c d]. - Compute M + M, M × M and M to the power k, using your operators.
Input
One line with the four numbers of M, row by row, and then k.
Output
Three lines: M + M, M × M, and M to the power k.
Constraints
Each number is from -10 to 10, and 0 ≤ k ≤ 10.
Example
Input:
1 1 1 0 10
Output:
[2 2; 2 0]
[2 1; 1 1]
[89 55; 55 34]
Why it works
Each operator is an ordinary function, so r = r * m reads like the maths while calling operator*. The power starts at the identity matrix because it changes nothing when multiplied, just as 1 does for numbers.
Examples
1 1 1 0 10
[2 2; 2 0] [2 1; 1 1] [89 55; 55 34]
2 0 0 2 3
[4 0; 0 4] [4 0; 0 4] [8 0; 0 8]
Hints
Hint 1
Store the four numbers as `long long`, and write `operator+`, `operator*` and a friend `operator<<`.
Hint 2
In a product, the cell in row i and column j is the sum over k of `a[i][k] * b[k][j]`.
Hint 3
Start the power at the identity matrix `[1 0; 0 1]` and multiply by M, k times.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
class Matrix {
long long a, b, c, d;
public:
Matrix(long long a, long long b, long long c, long long d) : a(a), b(b), c(c), d(d) {}
Matrix operator+(const Matrix& o) const {
return Matrix(a + o.a, b + o.b, c + o.c, d + o.d);
}
Matrix operator*(const Matrix& o) const {
return Matrix(a * o.a + b * o.c, a * o.b + b * o.d,
c * o.a + d * o.c, c * o.b + d * o.d);
}
friend ostream& operator<<(ostream& out, const Matrix& m);
};
ostream& operator<<(ostream& out, const Matrix& m) {
out << "[" << m.a << " " << m.b << "; " << m.c << " " << m.d << "]";
return out;
}
int main() {
long long a, b, c, d;
int k;
cin >> a >> b >> c >> d >> k;
Matrix m(a, b, c, d);
cout << m + m << endl;
cout << m * m << endl;
Matrix r(1, 0, 0, 1);
for (int i = 0; i < k; i++) r = r * m;
cout << r << endl;
return 0;
}