Open in App
Not now

# C++ Program to check idempotent matrix

• Last Updated : 29 Dec, 2022

Given N * N matrix and the task is to check matrix is an idempotent matrix or not.
Idempotent matrix: A matrix is said to be an idempotent matrix if the matrix multiplied by itself returns the same matrix. The matrix M is said to be an idempotent matrix if and only if M * M = M. In an idempotent matrix M is a square matrix.

Examples:

```Input : mat[][] = {{3, -6},
{1, -2}};
Output : Idempotent Matrix

Input : mat[N][N] = {{2, -2, -4},
{-1, 3, 4},
{1, -2, -3}}
Output : Idempotent Matrix.
```

## C++

 `// Program to check given matrix ` `// is idempotent matrix or not.` `#include` `#define N 3` `using` `namespace` `std;`   `// Function for matrix multiplication.` `void` `multiply(``int` `mat[][N], ``int` `res[][N])` `{` `    ``for` `(``int` `i = 0; i < N; i++)` `    ``{` `        ``for` `(``int` `j = 0; j < N; j++)` `        ``{` `            ``res[i][j] = 0;` `            ``for` `(``int` `k = 0; k < N; k++)` `                ``res[i][j] += mat[i][k] * mat[k][j];` `        ``}` `    ``}` `}`   `// Function to check idempotent` `// property of matrix.` `bool` `checkIdempotent(``int` `mat[][N])` `{   ` `    ``// Calculate multiplication of matrix` `    ``// with itself and store it into res.` `    ``int` `res[N][N];` `    ``multiply(mat, res);`   `    ``for` `(``int` `i = 0; i < N; i++)    ` `        ``for` `(``int` `j = 0; j < N; j++)        ` `            ``if` `(mat[i][j] != res[i][j])` `                ``return` `false``;` `    ``return` `true``;` `}`   `// Driver function.` `int` `main()` `{` `    ``int` `mat[N][N] = {{2, -2, -4},` `                    ``{-1, 3, 4},` `                    ``{1, -2, -3}};` `    `  `    ``// checkIdempotent function call.` `    ``if` `(checkIdempotent(mat))` `        ``cout << ``"Idempotent Matrix"``;` `    ``else` `        ``cout << ``"Not Idempotent Matrix."``;` `    ``return` `0;` `}`

Output

`Idempotent Matrix`

Time Complexity: O(N3)
Auxiliary Space: O(N2)

Please refer complete article on Program to check idempotent matrix for more details!

My Personal Notes arrow_drop_up
Related Articles