C++ 语言编写程序,检查幂等矩阵
假设 M[r][c] 是一个矩阵,“r”表示行数,“c”表示列数,其中 r = c 表示一个方阵。我们要检查给定的方阵是不是一个幂等矩阵。
幂等矩阵
如果并且仅当矩阵“M”与自身相乘等于“M”,则矩阵“M”被称为幂等矩阵,即 M * M = M.
比如以下示例 −
我们可以说,上述矩阵与自身相乘等于自身,因此该矩阵是幂等矩阵。
示例
Input: m[3][3] = { {2, -2, -4}, {-1, 3, 4}, {1, -2, -3}} Output: Idempotent Input: m[3][3] == { {3, 0, 0}, {0, 2, 0}, {0, 0, 3} } Output: Not Idempotent
算法
Start Step 1 -> define macro as #define size 3 Step 2 -> declare function for matrix multiplication void multiply(int arr[][size], int res[][size]) Loop For int i = 0 and i < size and i++ Loop For int j = 0 and j < size and j++ Set res[i][j] = 0 Loop for int k = 0 and k < size and k++ Set res[i][j] += arr[i][k] * arr[k][j] End End End Step 3 -> declare function to check idempotent or not bool check(int arr[][size]) declare int res[size][size] call multiply(arr, res) Loop For int i = 0 and i < size and i++ Loop For int j = 0 and j < size and j++ IF (arr[i][j] != res[i][j]) return false End End End return true step 4 -> In main() declare int arr[size][size] = {{1, -1, -1}, {-1, 1, 1}, {1, -1, -1}} IF (check(arr)) Print its an idempotent matrix Else Print its not an idempotent matrix Stop
示例
#include<bits/stdc++.h> #define size 3 using namespace std; //matrix multiplication. void multiply(int arr[][size], int res[][size]){ for (int i = 0; i < size; i++){ for (int j = 0; j < size; j++){ res[i][j] = 0; for (int k = 0; k < size; k++) res[i][j] += arr[i][k] * arr[k][j]; } } } //check idempotent or not bool check(int arr[][size]){ int res[size][size]; multiply(arr, res); for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) if (arr[i][j] != res[i][j]) return false; return true; } int main(){ int arr[size][size] = {{1, -1, -1}, {-1, 1, 1}, {1, -1, -1}}; if (check(arr)) cout << "its an idempotent matrix"; else cout << "its not an idempotent matrix"; return 0; }
输出
its an idempotent matrix
广告