Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptJavascript Program to check idempotent matrix

Javascript Program to check idempotent matrix

Given an 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.

idempotent 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.

Javascript




<script>
  
// Javascript program to check given matrix
// is idempotent matrix or not.
var N = 3;
 
// Function for matrix multiplication.
function multiply(mat, res)
{
    for (var i = 0; i < N; i++)
    {
        for (var j = 0; j < N; j++)
        {
            res[i][j] = 0;
            for (var k = 0; k < N; k++)
                res[i][j] += mat[i][k] * mat[k][j];
        }
    }
    return res;
}
 
// Function to check idempotent
// property of matrix.
function checkIdempotent(mat)
{
 
    // Calculate multiplication of matrix
    // with itself and store it into res.
    var res = Array.from(Array(N), ()=>Array(N).fill(0));
    res = multiply(mat, res);
 
    for (var i = 0; i < N; i++)
    {
        for (var j = 0; j < N; j++)
        {
            if (mat[i][j] != res[i][j])
                return false;
        }
    }
    return true;
}
 
// Driver code
var mat = [[2, -2, -4],
            [-1, 3, 4],
            [1, -2, -3]];
             
// checkIdempotent function call.
if (checkIdempotent(mat))
    document.write( "Idempotent Matrix");
else
    document.write("Not Idempotent Matrix.");
 
// This code is contributed by noob2000.
</script>


Output:

Idempotent Matrix

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

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments