Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรมตรวจสอบ Idempotent Matrix ใน C++


ให้เมทริกซ์ M[r][c] r = c เป็นเมทริกซ์สี่เหลี่ยมจัตุรัส ตรวจสอบว่าเป็น Idempotent Matrix หรือไม่

Idempotent Matrix

เมทริกซ์ 'M' เรียกว่า Idempotent Matrix ก็ต่อเมื่อ M คูณตัวเองได้ M เอง คือ M * M = M

ตัวอย่าง −

โปรแกรมตรวจสอบ Idempotent Matrix ใน C++

เมทริกซ์คูณตัวเองได้ตัวเอง จึงเป็น Idempotent Matrix

ตัวอย่าง

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