Untitled
unknown
plain_text
2 years ago
2.0 kB
7
Indexable
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
// Hàm nhân 2 ma trận
void multiplyMatrices(int mat1[][MAX_SIZE], int mat2[][MAX_SIZE], int result[][MAX_SIZE], int n) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
result[i][j] = 0;
for (int k = 0; k < n; ++k) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
// Hàm chia để trị số mũ
void powerMatrix(int matrix[][MAX_SIZE], int result[][MAX_SIZE], int n, int exponent) {
int temp[MAX_SIZE][MAX_SIZE];
if (exponent == 0) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i == j) {
result[i][j] = 1;
} else {
result[i][j] = 0;
}
}
}
} else if (exponent == 1) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
result[i][j] = matrix[i][j];
}
}
} else {
powerMatrix(matrix, temp, n, exponent / 2);
multiplyMatrices(temp, temp, result, n);
if (exponent % 2 != 0) {
multiplyMatrices(matrix, result, temp, n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
result[i][j] = temp[i][j];
}
}
}
}
}
// Hàm in ma trận
void printMatrix(int matrix[][MAX_SIZE], int n) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
int main() {
int matrix[MAX_SIZE][MAX_SIZE] = {{1, 2}, {3, 4}};
int result[MAX_SIZE][MAX_SIZE];
int exponent = 3;
int n = 2; // Kích thước của ma trận
cout << "Matrix:" << endl;
printMatrix(matrix, n);
cout << "Exponentiation of matrix:" << endl;
powerMatrix(matrix, result, n, exponent);
printMatrix(result, n);
return 0;
}
Editor is loading...
Leave a Comment