The Wayback Machine - https://web.archive.org/web/20241116072125/https://www.geeksforgeeks.org/adjoint-inverse-matrix/
Open In App

Adjoint and Inverse of a Matrix

Last Updated : 01 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a square matrix, find the adjoint and inverse of the matrix. We strongly recommend you to refer determinant of matrix as a prerequisite for this. 

Adjoint (or Adjugate) of a matrix is the matrix obtained by taking the transpose of the cofactor matrix of a given square matrix is called its Adjoint or Adjugate matrix. The Adjoint of any square matrix ‘A’ (say) is represented as Adj(A). 

Example: 

5  -2  2  7
1   0  0  3
-3  1  5  0
3  -1 -9  4
For instance, the cofactor of the top left corner '5' is
 + |0   0   3|
...|1   5   0| = 3(1 * -9 - (-1) * 5) = -12.
...|-1 -9   4|
(The minor matrix is formed by deleting the row 
 and column of the given entry.)
As another sample, the cofactor of the top row corner '-2' is
  -|1   0  3|
...|-3  5  0| = - [1 (20 - 0) - 0 + 3 (27 - 15)] = -56.
...|3  -9  4|
Proceeding like this, we obtain the matrix
[-12  -56   4   4]
[76   208   4   4]
[-60  -82  -2  20]
[-36  -58  -10 12]
Finally, to get the adjoint, just take the previous
matrix's transpose:
[-12   76 -60  -36]
[-56  208 -82  -58]
[4     4   -2  -10]
[4     4   20   12] 

Important properties: 

Product of a square matrix A with its adjoint yields a diagonal matrix, where each diagonal entry is equal to determinant of A. 
i.e. 

A.adj(A) = det(A).I 
I  => Identity matrix of same order as of A.
det(A) => Determinant value of A 

A non-zero square matrix ‘A’ of order n is said to be invertible if there exists a unique square matrix ‘B’ of order n such that,

A.B = B.A = I
The matrix 'B' is said to be inverse of 'A'.
i.e.,  B = A-1
  • adj(AB) = (adj B).(adj A)
  • adj( k A) = kn-1 adj(A)
  • A-1 = (adj A) / |A|
  • (A-1)-1 = A
  • (AB)-1 = B-1A-1

How to find Adjoint? 

We follow the definition given above. 

Let A[N][N] be input matrix.
1) Create a matrix adj[N][N] store the adjoint matrix.
2) For every entry A[i][j] in input matrix where 0 <= i < N
   and 0 <= j < N.
    a) Find cofactor of A[i][j]
    b) Find sign of entry.  Sign is + if (i+j) is even else
       sign is odd.
    c) Place the cofactor at adj[j][i]

How to find Inverse? 

Inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. 
Using determinant and adjoint, we can easily find the inverse of a square matrix using the below formula,

  If det(A) != 0
    A-1 = adj(A)/det(A)
  Else
    "Inverse doesn't exist"  

Inverse is used to find the solution to a system of linear equations.

Below are implementations for finding adjoint and inverse of a matrix.  

C++
#include <iostream>
#include <vector>
using namespace std;

// Function to get cofactor of mat[p][q] in cof[][]. n is
// current dimension of mat[][]
void getCof(vector<vector<int>>& mat, vector<vector<int>>& cof, 
                                        int p, int q, int n) {
    int i = 0, j = 0;
    for (int row = 0; row < n; row++) {
        for (int col = 0; col < n; col++) {
            if (row != p && col != q) {
                cof[i][j++] = mat[row][col];
                if (j == n - 1) {
                    j = 0;
                    i++;
                }
            }
        }
    }
}

// Recursive function for finding determinant 
// of matrix mat of dimension n
int getDet(vector<vector<int>>& mat, int n) {
    if (n == 1) return mat[0][0];
    
    int det = 0;
  
    // To store cofactors
    vector<vector<int>> cof(mat.size(), vector<int>(mat.size()));
  
    int sign = 1;
    for (int f = 0; f < n; f++) {
        getCof(mat, cof, 0, f, n);
        det += sign * mat[0][f] * getDet(cof, n - 1);
        sign = -sign;
    }
    return det;
}

// Function to get adjoint of mat in adj
void adjoint(vector<vector<int>>& mat, vector<vector<int>>& adj) {
    int n = mat.size();
    if (n == 1) {
        adj[0][0] = 1;
        return;
    }
    
    int sign = 1;
    vector<vector<int>> cof(n, vector<int>(n));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            getCof(mat, cof, i, j, n);
            sign = ((i + j) % 2 == 0) ? 1 : -1;
            adj[j][i] = sign * getDet(cof, n - 1);
        }
    }
}

// Function to calculate and store inverse, returns 
// false if matrix is singular
bool inverse(vector<vector<int>>& mat, vector<vector<float>>& inv) {
    int n = mat.size();
    int det = getDet(mat, n);
    if (det == 0) {
        cout << "Singular matrix, can't find its inverse";
        return false;
    }

    vector<vector<int>> adj(n, vector<int>(n));
    adjoint(mat, adj);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            inv[i][j] = adj[i][j] / float(det);

    return true;
}

int main() {
    vector<vector<int>> mat = { { 5, -2, 2, 7 },
                                { 1, 0, 0, 3 },
                                { -3, 1, 5, 0 },
                                { 3, -1, -9, 4 } };

    int n = mat.size();
    vector<vector<int>> adj(n, vector<int>(n)); // To store adjoint
    vector<vector<float>> inv(n, vector<float>(n)); // To store inverse

    // Print the input matrix
    cout << "Input matrix is:\n";
    for (auto& row : mat) {
        for (int val : row) cout << val << " ";
        cout << endl;
    }

    // Print the adjoint matrix
    cout << "\nThe Adjoint is:\n";
    adjoint(mat, adj);
    for (auto& row : adj) {
        for (int val : row) cout << val << " ";
        cout << endl;
    }

    // Print the inverse matrix if it exists
    cout << "\nThe Inverse is:\n";
    if (inverse(mat, inv)) {
        for (auto& row : inv) {
            for (float val : row) cout << val << " ";
            cout << endl;
        }
    }

    return 0;
}
C
#include <stdio.h>

#define N 4

// Function to get cofactor of mat[p][q] in cof[][]. n is
// current dimension of mat[][]
void getCof(int mat[N][N], int cof[N][N], int p, int q, int n) {
    int i = 0, j = 0;
    for (int row = 0; row < n; row++) {
        for (int col = 0; col < n; col++) {
            if (row != p && col != q) {
                cof[i][j++] = mat[row][col];
                if (j == n - 1) {
                    j = 0;
                    i++;
                }
            }
        }
    }
}

// Recursive function for finding determinant of matrix mat of dimension n
int getDet(int mat[N][N], int n) {
    if (n == 1) return mat[0][0];
    int det = 0;
    
    int cof[N][N];
    int sign = 1;
    for (int f = 0; f < n; f++) {
        getCof(mat, cof, 0, f, n);
        det += sign * mat[0][f] * getDet(cof, n - 1);
        sign = -sign;
    }
    return det;
}

// Function to get adjoint of mat in adj
void adjoint(int mat[N][N], double adj[N][N]) {
    if (N == 1) {
        adj[0][0] = 1;
        return;
    }
    
    int sign = 1;
    int cof[N][N];
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            getCof(mat, cof, i, j, N);
            sign = ((i + j) % 2 == 0) ? 1 : -1;
            adj[j][i] = sign * getDet(cof, N - 1);
        }
    }
}

// Function to calculate and store inverse, returns 0 if matrix is singular
int inverse(int mat[N][N], double inv[N][N]) {
    int det = getDet(mat, N);
    if (det == 0) {
        printf("Singular matrix, can't find its inverse\n");
        return 0;
    }

    double adj[N][N];
    adjoint(mat, adj);

    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            inv[i][j] = adj[i][j] / det;

    return 1;
}

int main() {
    int mat[N][N] = { { 5, -2, 2, 7 },
                      { 1, 0, 0, 3 },
                      { -3, 1, 5, 0 },
                      { 3, -1, -9, 4 } };

    double adj[N][N];
    double inv[N][N];

    // Print the input matrix
    printf("Input matrix is:\n");
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }

    // Print the adjoint matrix
    printf("\nThe Adjoint is:\n");
    adjoint(mat, adj);
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            printf("%lf ", adj[i][j]);
        }
        printf("\n");
    }

    // Print the inverse matrix if it exists
    printf("\nThe Inverse is:\n");
    if (inverse(mat, inv)) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                printf("%lf ", inv[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}
Java
// Importing required classes
import java.util.Arrays;
import java.util.Scanner;

public class GfG {
  
    // Function to get cofactor of mat[p][q] in cof[][]
    static void getCof(int[][] mat, int[][] cof, int p, int q, int n) {
        int i = 0, j = 0;
        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n; col++) {
                if (row != p && col != q) {
                    cof[i][j++] = mat[row][col];
                    if (j == n - 1) {
                        j = 0;
                        i++;
                    }
                }
            }
        }
    }

    // Recursive function for finding determinant of
    // matrix mat of dimension n
    static int getDet(int[][] mat, int n) {
        if (n == 1) return mat[0][0];
        int det = 0;
        int[][] cof = new int[n][n];
        int sign = 1;
        for (int f = 0; f < n; f++) {
            getCof(mat, cof, 0, f, n);
            det += sign * mat[0][f] * getDet(cof, n - 1);
            sign = -sign;
        }
        return det;
    }

    // Function to get adjoint of mat in adj
    static void adjoint(int[][] mat, int[][] adj) {
        int n = mat.length;
        if (n == 1) {
            adj[0][0] = 1;
            return;
        }
        int sign;
        int[][] cof = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                getCof(mat, cof, i, j, n);
                sign = ((i + j) % 2 == 0) ? 1 : -1;
                adj[j][i] = sign * getDet(cof, n - 1);
            }
        }
    }

    // Function to calculate and store inverse, returns 
    // false if matrix is singular
    static boolean inverse(int[][] mat, float[][] inv) {
        int n = mat.length;
        int det = getDet(mat, n);
        if (det == 0) {
            System.out.println("Singular matrix, can't find its inverse");
            return false;
        }
        int[][] adj = new int[n][n];
        adjoint(mat, adj);
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                inv[i][j] = (float) adj[i][j] / det;
        return true;
    }

    public static void main(String[] args) {
        int[][] mat = { { 5, -2, 2, 7 }, { 1, 0, 0, 3 }, 
                        { -3, 1, 5, 0 }, { 3, -1, -9, 4 } };
        int n = mat.length;
        int[][] adj = new int[n][n]; // To store adjoint
        float[][] inv = new float[n][n]; // To store inverse

        // Print the input matrix
        System.out.println("Input matrix is:");
        for (int[] row : mat) {
            System.out.println(Arrays.toString(row));
        }

        // Print the adjoint matrix
        System.out.println("\nThe Adjoint is:");
        adjoint(mat, adj);
        for (int[] row : adj) {
            System.out.println(Arrays.toString(row));
        }

        // Print the inverse matrix if it exists
        System.out.println("\nThe Inverse is:");
        if (inverse(mat, inv)) {
            for (float[] row : inv) {
                System.out.println(Arrays.toString(row));
            }
        }
    }
}
Python
# Function to get cofactor of mat[p][q] in cof[][]
def get_cof(mat, cof, p, q, n):
    i = 0
    j = 0
    for row in range(n):
        for col in range(n):
            if row != p and col != q:
                cof[i][j] = mat[row][col]
                j += 1
                if j == n - 1:
                    j = 0
                    i += 1

# Recursive function for finding determinant
# of matrix mat of dimension n
def get_det(mat, n):
    if n == 1:
        return mat[0][0]
    det = 0
    cof = [[0] * n for _ in range(n)]  # To store cofactors
    sign = 1
    for f in range(n):
        get_cof(mat, cof, 0, f, n)
        det += sign * mat[0][f] * get_det(cof, n - 1)
        sign = -sign
    return det

# Function to get adjoint of mat in adj
def adjoint(mat, adj):
    n = len(mat)
    if n == 1:
        adj[0][0] = 1
        return
    sign = 1
    cof = [[0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            get_cof(mat, cof, i, j, n)
            sign = 1 if (i + j) % 2 == 0 else -1
            adj[j][i] = sign * get_det(cof, n - 1)

# Function to calculate and store inverse, returns 
# false if matrix is singular
def inverse(mat):
    n = len(mat)
    det = get_det(mat, n)
    if det == 0:
        print("Singular matrix, can't find its inverse")
        return None
    adj = [[0] * n for _ in range(n)]
    adjoint(mat, adj)
    inv = [[adj[i][j] / det for j in range(n)] for i in range(n)]
    return inv

if __name__ == '__main__':
    mat = [[5, -2, 2, 7], [1, 0, 0, 3], [-3, 1, 5, 0], [3, -1, -9, 4]]
    n = len(mat)
    adj = [[0] * n for _ in range(n)]  # To store adjoint

    # Print the input matrix
    print("Input matrix is:")
    for row in mat:
        print(row)

    # Print the adjoint matrix
    print("\nThe Adjoint is:")
    adjoint(mat, adj)
    for row in adj:
        print(row)

    # Print the inverse matrix if it exists
    print("\nThe Inverse is:")
    inv = inverse(mat)
    if inv:
        for row in inv:
            print(row)
C#
using System;

class MatrixOperations {
  
    // Function to get cofactor of mat[p][q] in cof[][]. n is
    // current dimension of mat[][]
    static void GetCof(int[,] mat, int[,] cof, int p, int q, int n) {
        int i = 0, j = 0;
        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n; col++) {
                if (row != p && col != q) {
                    cof[i, j++] = mat[row, col];
                    if (j == n - 1) {
                        j = 0;
                        i++;
                    }
                }
            }
        }
    }

    // Recursive function for finding determinant of matrix mat of dimension n
    static int GetDet(int[,] mat, int n) {
        if (n == 1) return mat[0, 0];
        int det = 0;

        // To store cofactors
        int[,] cof = new int[n, n];

        int sign = 1;
        for (int f = 0; f < n; f++) {
            GetCof(mat, cof, 0, f, n);
            det += sign * mat[0, f] * GetDet(cof, n - 1);
            sign = -sign;
        }
        return det;
    }

    // Function to get adjoint of mat in adj
    static void Adjoint(int[,] mat, double[,] adj) {
        int n = mat.GetLength(0);
        if (n == 1) {
            adj[0, 0] = 1;
            return;
        }

        int sign = 1;
        int[,] cof = new int[n, n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                GetCof(mat, cof, i, j, n);
                sign = ((i + j) % 2 == 0) ? 1 : -1;
                adj[j, i] = sign * GetDet(cof, n - 1);
            }
        }
    }

    // Function to calculate and store inverse, returns false if matrix is singular
    static bool Inverse(int[,] mat, double[,] inv) {
        int n = mat.GetLength(0);
        int det = GetDet(mat, n);
        if (det == 0) {
            Console.WriteLine("Singular matrix, can't find its inverse");
            return false;
        }

        double[,] adj = new double[n, n];
        Adjoint(mat, adj);

        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                inv[i, j] = adj[i, j] / det;

        return true;
    }

    static void Main() {
        int[,] mat = new int[,] { { 5, -2, 2, 7 },
                                   { 1, 0, 0, 3 },
                                   { -3, 1, 5, 0 },
                                   { 3, -1, -9, 4 } };
        int n = mat.GetLength(0);
        double[,] adj = new double[n, n]; // To store adjoint
        double[,] inv = new double[n, n]; // To store inverse

        // Print the input matrix
        Console.WriteLine("Input matrix is:");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Console.Write(mat[i, j] + " ");
            }
            Console.WriteLine();
        }

        // Print the adjoint matrix
        Console.WriteLine("\nThe Adjoint is:");
        Adjoint(mat, adj);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Console.Write(adj[i, j] + " ");
            }
            Console.WriteLine();
        }

        // Print the inverse matrix if it exists
        Console.WriteLine("\nThe Inverse is:");
        if (Inverse(mat, inv)) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    Console.Write(inv[i, j] + " ");
                }
                Console.WriteLine();
            }
        }
    }
}
JavaScript
// Function to get cofactor of mat[p][q] in cof[][]. n is
// current dimension of mat[][]
function getCof(mat, cof, p, q, n) {
    let i = 0, j = 0;
    for (let row = 0; row < n; row++) {
        for (let col = 0; col < n; col++) {
            if (row !== p && col !== q) {
                cof[i][j++] = mat[row][col];
                if (j === n - 1) {
                    j = 0;
                    i++;
                }
            }
        }
    }
}

// Recursive function for finding determinant 
// of matrix mat of dimension n
function getDet(mat, n) {
    if (n === 1) return mat[0][0];
    let det = 0;
    
    // To store cofactors
    let cof = Array.from({ length: mat.length }, () => Array(mat.length).fill(0));
    
    let sign = 1;
    for (let f = 0; f < n; f++) {
        getCof(mat, cof, 0, f, n);
        det += sign * mat[0][f] * getDet(cof, n - 1);
        sign = -sign;
    }
    return det;
}

// Function to get adjoint of mat in adj
function adjoint(mat, adj) {
    let n = mat.length;
    if (n === 1) {
        adj[0][0] = 1;
        return;
    }
    
    let sign = 1;
    let cof = Array.from({ length: n }, () => Array(n).fill(0));
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            getCof(mat, cof, i, j, n);
            sign = ((i + j) % 2 === 0) ? 1 : -1;
            adj[j][i] = sign * getDet(cof, n - 1);
        }
    }
}

// Function to calculate and store inverse, returns 
// false if matrix is singular
function inverse(mat, inv) {
    let n = mat.length;
    let det = getDet(mat, n);
    if (det === 0) {
        console.log("Singular matrix, can't find its inverse");
        return false;
    }

    let adj = Array.from({ length: n }, () => Array(n).fill(0));
    adjoint(mat, adj);

    for (let i = 0; i < n; i++)
        for (let j = 0; j < n; j++)
            inv[i][j] = adj[i][j] / det;

    return true;
}

let mat = [ [ 5, -2, 2, 7 ],
            [ 1, 0, 0, 3 ],
            [ -3, 1, 5, 0 ],
            [ 3, -1, -9, 4 ] ];

let n = mat.length;
let adj = Array.from({ length: n }, () => Array(n).fill(0)); // To store adjoint
let inv = Array.from({ length: n }, () => Array(n).fill(0)); // To store inverse

// Print the input matrix
console.log("Input matrix is:");
mat.forEach(row => {
    console.log(row.join(' '));
});

// Print the adjoint matrix
console.log("\nThe Adjoint is:");
adjoint(mat, adj);
adj.forEach(row => {
    console.log(row.join(' '));
});

// Print the inverse matrix if it exists
console.log("\nThe Inverse is:");
if (inverse(mat, inv)) {
    inv.forEach(row => {
        console.log(row.join(' '));
    });
}

Output
Input matrix is:
5 -2 2 7 
1 0 0 3 
-3 1 5 0 
3 -1 -9 4 

The Adjoint is:
-12 76 -60 -36 
-56 208 -82 -58 
4 4 -2 -10 
4 4 20 12 

The Inverse is:
-0.136364 0.863636 -0.681818 -0.409091 
-0.636364 2.36364 -0.931818 -0.659091 
0.0454545 0.0454545 -0.0227273 -0.113636 
0.0454545 0.0454545 0.227273 0.136364 

Please refer determinant of matrix for details of getCofactor() and determinant().

 



Previous Article
Next Article

Similar Reads

Finding Inverse of a Square Matrix using Cayley Hamilton Theorem in MATLAB
Matrix is the set of numbers arranged in rows & columns in order to form a Rectangular array. Here, those numbers are called the entries or elements of that matrix. A Rectangular array of (m*n) numbers in the form of 'm' horizontal lines (rows) & 'n' vertical lines (called columns), is called a matrix of order m by n, which is written as m
4 min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Find sum of inverse of the divisors when sum of divisors and the number is given
Given an integer N and the sum of its divisors. The task is to find the sum of the inverse of the divisors of N.Examples: Input: N = 6, Sum = 12 Output: 2.00 Divisors of N are {1, 2, 3, 6} Sum of inverse of divisors is equal to (1/1 + 1/2 + 1/3 + 1/6) = 2.0Input: N = 9, Sum = 13 Output: 1.44 Naive Approach: Calculate all the divisors of the given i
3 min read
Decimal Equivalent of Gray Code and its Inverse
Given a decimal number n. Find the gray code of this number in decimal form. Examples: Input : 7 Output : 4 Explanation: 7 is represented as 111 in binary form. The equivalent gray code of 111 is 100 in binary form, whose decimal equivalent is 4. Input : 10 Output : 15 Explanation: 10 is represented as 1010 in binary form. The equivalent gray code
7 min read
Inverse Permutation
Given an array of size n of integers in range from 1 to n, we need to find the inverse permutation of that array. An inverse permutation is a permutation which you will get by inserting position of an element at the position specified by the element value in the array. For better understanding, consider the following example: Suppose we found eleme
9 min read
Inverse Ackermann Function
The inverse Ackermann function is the inverse of the Ackermann function, which is a mathematical function defined as follows: A(m, n) = n+1, if m = 0A(m-1, 1), if m > 0 and n = 0A(m-1, A(m, n-1)), if m > 0 and n > 0 The inverse Ackermann function is the function that returns the pair of integers (m, n) that satisfies the equation A(m, n) =
7 min read
Program to implement Inverse Interpolation using Lagrange Formula
Given task is to find the value of x for a given y of an unknown function y = f(x) where values of some points (x, y) pairs are given.Let, y = f(x) be an unknown function where x in an independent variable. For different values of x, say [Tex]x_0, x_1, x_2, ..., x_m ( i.e [/Tex][Tex]x_k, k=0, 1, 2, 3...m) [/Tex]values of respective [Tex]y_0, y_1, y
8 min read
Append the elements of queue in mirror-inverse order
Given a queue Q containing N strings, the task is to restructure the queue to double its size such that the second half represents the mirror image of the first half.Examples: Input: Q = {"Hello", "World"} Output: {"Hello", "World", "World", "Hello"} Explanation: The second half of the output queue is the mirror image of the first half. That is: "H
6 min read
Check if the given array is same as its inverse permutation
Given an array arr[] consisting of integers in the range [1, N], the task is to determine whether the Inverse Permutation of the given array is same as the given array. An inverse permutation is a permutation obtained by inserting the position of all elements at the position equal to the respective values of the element in the array.Illustration: a
8 min read
Count array elements having modular inverse under given prime number P equal to itself
Given an array arr[] of size N and a prime number P, the task is to count the elements of the array such that modulo multiplicative inverse of the element under modulo P is equal to the element itself. Examples: Input: arr[] = {1, 6, 4, 5}, P = 7Output: 2Explanation:Modular multiplicative inverse of arr[0](=1) under modulo P(= 7) is arr[0](= 1) its
5 min read
XOR of array elements whose modular inverse with a given number exists
Given an array arr[] of length N and a positive integer M, the task is to find the Bitwise XOR of all the array elements whose modular inverse with M exists. Examples: Input: arr[] = {1, 2, 3}, M = 4Output: 2Explanation:Initialize the value xor with 0:For element indexed at 0 i.e., 1, its mod inverse with 4 is 1 because (1 * 1) % 4 = 1 i.e., it exi
7 min read
Nearest smaller number to N having multiplicative inverse under modulo N equal to that number
Given a prime number N, the task is to find the closest smaller number than N such that modulo multiplicative inverse of a number under modulo N is equal to the number itself. Examples: Input: N = 7Output: 6Explanation:Modulo multiplicative inverse of all possible natural numbers from 1 to less than N are:Modulo multiplicative inverse of 1 under mo
3 min read
Program to print a inverse pyramid character pattern
Given a positive integer n, print the inverse pyramid pattern upto n rows as shown in the examples.Examples : Input : 4 Output : A B C D D C B A A B C C B A A B B A A A Input : 6 Output : A B C D E F F E D C B A A B C D E E D C B A A B C D D C B A A B C C B A A B B A A A Below is the implementation for the pattern: C/C++ Code // C++ code to print i
6 min read
Modular multiplicative inverse from 1 to n
Give a positive integer n, find modular multiplicative inverse of all integer from 1 to n with respect to a big prime number, say, 'prime'. The modular multiplicative inverse of a is an integer 'x' such that. a x ? 1 (mod prime) Examples: Input : n = 10, prime = 17 Output : 1 9 6 13 7 3 5 15 2 12 Explanation : For 1, modular inverse is 1 as (1 * 1)
9 min read
Python | Inverse Fast Fourier Transformation
Inverse Fast Fourier transform (IDFT) is an algorithm to undoes the process of DFT. It is also known as backward Fourier transform. It converts a space or time signal to a signal of the frequency domain. The DFT signal is generated by the distribution of value sequences to different frequency components. Working directly to convert on Fourier trans
2 min read
Fast method to calculate inverse square root of a floating point number in IEEE 754 format
Given a 32-bit floating point number x stored in IEEE 754 floating point format, find the inverse square root of x, i.e., x-1/2.A simple solution is to do floating point arithmetic. Following is an example function. C/C++ Code #include <bits/stdc++.h> using namespace std; float InverseSquareRoot(float x) { return 1/sqrt(x); } int main() { cou
4 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Inverse Graph
What is Inverse Graph?Inverse of a directed graph G is another directed graph on the same set of vertices with all the edges reversed as present in G. For every directed edge (u, v) present in G, the inverse of the graph has the directed edge (v, u). Why to use Inverse Graph?The idea behind using Inverse Graph is to analyze paths and connectivity o
10 min read
Modular multiplicative inverse
Given two integers A and M, find the modular multiplicative inverse of A under modulo M.The modular multiplicative inverse is an integer X such that: A * X ≡ 1 (mod M) Note: The value of X should be in the range {1, 2, ... M-1}, i.e., in the range of integer modulo M. ( Note that X cannot be 0 as A*0 mod M will never be 1). The multiplicative inver
15+ min read
Check if a given matrix can be converted to another given matrix by row and column exchanges
Given a matrix startMatrix and another matrix finalMatrix, the task is to check if startMatrix can be converted to finalMatrix by column exchanges and a row exchanges. Examples: Input: start[][] = {{1, 2, 3, 4}, {5, 6, 7, 8} {9, 10, 11, 12}, {13, 14, 15, 16}}final[][] = {{1, 4, 3, 2}, {5, 8, 7, 6}, {13, 16, 15, 14}, {9, 12, 11, 10}} Output: Yes Exp
9 min read
Convert given Matrix into a Symmetric Matrix by replacing elements at (i, j) and (j, i) with their mean
Given an integer N and a N x N matrix, the task is to convert the given matrix into a symmetric matrix by replacing (i, j)th and (j, i)th element with their arithmetic mean. Examples: Input: arr[] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output: 1 3 53 5 75 7 9Explanation: The diagonal elements are same. The element at index (0, 1) = 2 and (1, 0) = 4 is
6 min read
Find the original matrix from the given AND matrix
Given a binary matrix B[][] of size N*M, the task is to find a matrix A[][] of the same size such that B[i][j] is the bitwise AND of all the elements in ith row and jth column of A[][]. Examples: Input: B[][] = { {1, 0, 1}, {0, 0, 0} }Output: { {1, 1, 1}, {1, 0, 1} }Explanation:1 1 1 ? 1 0 11 0 1 0 0 0 Input: B[][] = { {0, 0}, {1, 1} }Output: -1 Ap
10 min read
Set entire Matrix row and column as Zeroes (Set Matrix Zeroes)
Given a Matrix arr of size M x N, the task is to set all rows and columns to zeroes if a particular element is zero, in constant space complexity. Examples: Input: [ [1, 1, 1], [1, 0, 1], [1, 1, 1]]Output: [ [1, 0, 1], [0, 0, 0], [1, 0, 1]]Explanation: one zero is present at cell(2,2), and all the elements in the 2nd row and 2nd column are marked a
15+ min read
Program to check diagonal matrix and scalar matrix
Diagonal matrixA square matrix is said to be a diagonal matrix if the elements of the matrix except the main diagonal are zero. A square null matrix is also a diagonal matrix whose main diagonal elements are zero. Examples: Input: Mat[4][4] = {{4, 0, 0, 0}, {0, 5, 0, 0}, {0, 0, 2, 0}, {0, 0, 0, 1}}Output: YesInput:Mat[4][4] = {{6, 10, 12, 0}, {0, 5
10 min read
Check if it is possible to make the given matrix increasing matrix or not
Given a matrix of N X M of positive integers, the task is to find out whether it is possible to make the matrix increasing or not. Print the matrix constructed otherwise print -1. Matrix elements should be greater than zero. A matrix is said to be increasing matrix if: For each row, the elements are in the increasing order.For each column, the elem
10 min read
Program to check if a matrix is Binary matrix or not
Given a matrix, the task is to check if that matrix is a Binary Matrix. A Binary Matrix is a matrix in which all the elements are either 0 or 1. It is also called Logical Matrix, Boolean Matrix, Relation Matrix. Examples: Input: {{1, 0, 1, 1}, {0, 1, 0, 1} {1, 1, 1, 0}} Output: Yes Input: {{1, 0, 1, 1}, {1, 2, 0, 1}, {0, 0, 1, 1}} Output: No Approa
5 min read
Program to convert given Matrix to a Diagonal Matrix
Given a N*N matrix. The task is to convert the matrix to a diagonal matrix. That is to change the values of the non-diagonal elements of a matrix to 0.Diagonal-Matrix: A matrix is called a Diagonal Matrix if all the non-diagonal elements of the matrix are zero.Examples: Input : mat[][] = {{ 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 }} Output : {{2, 0, 7},
8 min read
Check if matrix can be converted to another matrix by transposing square sub-matrices
Given two N X M matrices of integers. In an operation, we can transpose any square sub-matrix in matrix1. The task is to check if matrix1 can be converted to matrix2 with the given operation.Examples: Input: matrix1[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, matrix2[][] = { {1, 4, 7}, {2, 5, 6}, {3, 8, 9}} Output: Yes Transpose the whole matrix and
10 min read
Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B
Given two binary matrices, A[][] and B[][] of size N×M, the task is to find the minimum number of swaps of the elements of matrix A, needed to convert matrix A into matrix B. If it is impossible to do so then print "-1". Examples : Input: A[][] = {{1, 1, 0}, {0, 0, 1}, {0, 1, 0}}, B[][] = {{0, 0, 1}, {0, 1, 0}, {1, 1, 0}}Output: 3Explanation: One p
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg