Given two integers N and M. Consider two matrix ANXM, BNXM. Both matrix A and matrix B contains elements from 1 to N*M. Matrix A contains elements in Row-major order and matrix B contains elements in Column-major order. The task is to find the trace of the matrix formed by addition of A and B. Trace of matrix PNXM is defined as P[0][0] + P[1][1] + P[2][2] +….. + P[min(n – 1, m – 1)][min(n – 1, m – 1)] i.e addition of main diagonal.
Note – Both matrix A and matrix B contain elements from 1 to N*M.
Examples :Â
Input : N = 3, M = 3 Output : 30 Therefore, 1 2 3 A = 4 5 6 7 8 9 1 4 7 B = 2 5 8 3 6 9 2 6 10 A + B = 6 10 14 10 14 18 Trace = 2 + 10 + 18 = 30
Method 1 (Naive Approach): Generate matrix A and B and find the sum. Then traverse the main diagonal and find the sum.
Below is the implementation of this approach:Â Â
C++
// C++ program to find // trace of matrix formed by // adding Row-major and // Column-major order of same matrix #include <bits/stdc++.h> using namespace std; Â
// Return the trace of // sum of row-major matrix // and column-major matrix int trace( int n, int m) { Â
    int A[n][m], B[n][m], C[n][m];   Â
    // Generating the matrix A     int cnt = 1;     for ( int i = 0; i < n; i++)         for ( int j = 0; j < m; j++) {             A[i][j] = cnt;             cnt++;         }   Â
    // Generating the matrix A     cnt = 1;     for ( int i = 0; i < n; i++)         for ( int j = 0; j < m; j++) {             B[j][i] = cnt;             cnt++;         } Â
    // Finding sum of matrix A and matrix B     for ( int i = 0; i < n; i++)         for ( int j = 0; j < m; j++)             C[i][j] = A[i][j] + B[i][j];   Â
    // Finding the trace of matrix C.     int sum = 0;     for ( int i = 0; i < n; i++)         for ( int j = 0; j < m; j++)             if (i == j)                 sum += C[i][j]; Â
    return sum; } Â
// Driven Program int main() { Â Â Â Â int N = 3, M = 3; Â Â Â Â cout << trace(N, M) << endl; Â Â Â Â return 0; } |
Java
// Java program to find // trace of matrix formed by // adding Row-major and // Column-major order of same matrix import java.io.*; Â
public class GFG {     // Return the trace of     // sum of row-major matrix     // and column-major matrix     static int trace( int n, int m)     {              int A[][] = new int [n][m];         int B[][] = new int [n][m];         int C[][] = new int [n][m];              // Generating the matrix A         int cnt = 1 ;         for ( int i = 0 ; i < n; i++)             for ( int j = 0 ; j < m; j++) {                 A[i][j] = cnt;                 cnt++;             }              // Generating the matrix A         cnt = 1 ;         for ( int i = 0 ; i < n; i++)             for ( int j = 0 ; j < m; j++) {                 B[j][i] = cnt;                 cnt++;             }              // Finding sum of matrix A and matrix B         for ( int i = 0 ; i < n; i++)             for ( int j = 0 ; j < m; j++)                 C[i][j] = A[i][j] + B[i][j];              // Finding the trace of matrix C.         int sum = 0 ;         for ( int i = 0 ; i < n; i++)             for ( int j = 0 ; j < m; j++)                 if (i == j)                     sum += C[i][j];              return sum;     }          // Driver code     public static void main (String[] args)     {         int N = 3 , M = 3 ;                  System.out.println(trace(N, M));     } } Â
// This code is contributed by Anant Agarwal. |
Python3
# Python3 program to find trace of matrix # formed by adding Row-major and # Column-major order of same matrix Â
# Return the trace of sum of row-major # matrix and column-major matrix def trace(n, m): Â
    A = [[ 0 for x in range (m)]             for y in range (n)];     B = [[ 0 for x in range (m)]             for y in range (n)];     C = [[ 0 for x in range (m)]             for y in range (n)]; Â
    # Generating the matrix A     cnt = 1 ;     for i in range (n):         for j in range (m):             A[i][j] = cnt;             cnt + = 1 ; Â
    # Generating the matrix A     cnt = 1 ;     for i in range (n):         for j in range (m):             B[j][i] = cnt;             cnt + = 1 ; Â
    # Finding sum of matrix A and matrix B     for i in range (n):         for j in range (m):             C[i][j] = A[i][j] + B[i][j]; Â
    # Finding the trace of matrix C.     sum = 0 ;     for i in range (n):         for j in range (m):             if (i = = j):                 sum + = C[i][j]; Â
    return sum ; Â
# Driver Code N = 3 ; M = 3 ; print (trace(N, M)); Â Â Â Â Â # This code is contributed by mits |
C#
// C# program to find // trace of matrix formed by // adding Row-major and // Column-major order of same matrix using System; Â
class GFG {          // Return the trace of     // sum of row-major matrix     // and column-major matrix     static int trace( int n, int m)     {         int [, ] A = new int [n, m];         int [, ] B = new int [n, m];         int [, ] C = new int [n, m]; Â
        // Generating the matrix A         int cnt = 1;         for ( int i = 0; i < n; i++)             for ( int j = 0; j < m; j++) {                 A[i, j] = cnt;                 cnt++;             } Â
        // Generating the matrix A         cnt = 1;         for ( int i = 0; i < n; i++)             for ( int j = 0; j < m; j++) {                 B[j, i] = cnt;                 cnt++;             } Â
        // Finding sum of matrix A and matrix B         for ( int i = 0; i < n; i++)             for ( int j = 0; j < m; j++)                 C[i, j] = A[i, j] + B[i, j]; Â
        // Finding the trace of matrix C.         int sum = 0;         for ( int i = 0; i < n; i++)             for ( int j = 0; j < m; j++)                 if (i == j)                     sum += C[i, j]; Â
        return sum;     } Â
    // Driver code     public static void Main()     {         int N = 3, M = 3;         Console.WriteLine(trace(N, M));     } } Â
// This code is contributed by vt_m. |
PHP
<?php // PHP program to find trace of matrix // formed by adding Row-major and // Column-major order of same matrix Â
// Return the trace of sum of row-major // matrix and column-major matrix function trace( $n , $m ) { Â
    $A = array_fill (0, $n , array_fill (0, $m , 0));     $B = array_fill (0, $n , array_fill (0, $m , 0));     $C = array_fill (0, $n , array_fill (0, $m , 0)); Â
    // Generating the matrix A     $cnt = 1;     for ( $i = 0; $i < $n ; $i ++)         for ( $j = 0; $j < $m ; $j ++)         {             $A [ $i ][ $j ] = $cnt ;             $cnt ++;         } Â
    // Generating the matrix A     $cnt = 1;     for ( $i = 0; $i < $n ; $i ++)         for ( $j = 0; $j < $m ; $j ++)         {             $B [ $j ][ $i ] = $cnt ;             $cnt ++;         } Â
    // Finding sum of matrix A and matrix B     for ( $i = 0; $i < $n ; $i ++)         for ( $j = 0; $j < $m ; $j ++)             $C [ $i ][ $j ] = $A [ $i ][ $j ] + $B [ $i ][ $j ]; Â
    // Finding the trace of matrix C.     $sum = 0;     for ( $i = 0; $i < $n ; $i ++)         for ( $j = 0; $j < $m ; $j ++)             if ( $i == $j )                 $sum += $C [ $i ][ $j ]; Â
    return $sum ; } Â
// Driver Code $N = 3; $M = 3; print (trace( $N , $M )); Â Â Â Â Â // This code is contributed by mits ?> |
Javascript
<script> Â
// Javascript program to find // trace of matrix formed by // adding Row-major and // Column-major order of same matrix Â
// Return the trace of // sum of row-major matrix // and column-major matrix function trace(n, m) {        let A = new Array(n);          // Loop to create 2D array using 1D array     for ( var i = 0; i < A.length; i++)     {         A[i] = new Array(2);     }          let B = new Array(n);          // Loop to create 2D array using 1D array     for ( var i = 0; i < B.length; i++)     {         B[i] = new Array(2);     }          let C = new Array(n);          // Loop to create 2D array using 1D array     for ( var i = 0; i < C.length; i++)     {         C[i] = new Array(2);     }          // Generating the matrix A     let cnt = 1;     for (let i = 0; i < n; i++)         for (let j = 0; j < m; j++)         {             A[i][j] = cnt;             cnt++;         }          // Generating the matrix A     cnt = 1;     for (let i = 0; i < n; i++)         for (let j = 0; j < m; j++)         {             B[j][i] = cnt;             cnt++;         }          // Finding sum of matrix A and matrix B     for (let i = 0; i < n; i++)         for (let j = 0; j < m; j++)             C[i][j] = A[i][j] + B[i][j];          // Finding the trace of matrix C.     let sum = 0;     for (let i = 0; i < n; i++)         for (let j = 0; j < m; j++)             if (i == j)                 sum += C[i][j];          return sum; } Â
// Driver code let N = 3, M = 3; Â Â Â document.write(trace(N, M)); Â
// This code is contributed by susmitakundugoaldanga Â
</script> |
30
Time Complexity: O(N*M), as we are traversing the matrix using nested loops.
Auxiliary Space: O(N*M), as we are using extra space.
Method 2 (efficient approach) :Â
Basically, we need to find the sum of main diagonal of the first matrix A and main diagonal of the second matrix B.Â
Let’s take an example, N = 3, M = 4.Â
Therefore, Row-major matrix will be,Â
1 2 3 4 A = 5 6 7 8 9 10 11 12
So, we need the sum of 1, 6, 11.Â
Observe, it forms an Arithmetic Progression with a constant difference of a number of columns, M.Â
Also, first element is always 1. So, AP formed in case of Row-major matrix is 1, 1+(M+1), 1+2*(M+1), ….. consisting of N (number of rows) elements. And we know,Â
Sn = (n * (a1 + an))/2Â
So, n = R, a1 = 1, an = 1 + (R – 1)*(M+1).
Similarly, in case of Column-major, AP formed will be 1, 1+(N+1), 1+2*(N+1), …..Â
So, n = R, a1 = 1, an = 1 + (R – 1)*(N+1).
Below is the implementation of this approach:Â Â
C++
// C++ program to find trace of matrix formed // by adding Row-major and Column-major order // of same matrix #include <bits/stdc++.h> using namespace std; Â
// Return sum of first n integers of an AP int sn( int n, int an) { Â Â Â Â return (n * (1 + an)) / 2; } Â
// Return the trace of sum of row-major matrix // and column-major matrix int trace( int n, int m) {     // Finding nth element in     // AP in case of Row major matrix.     int an = 1 + (n - 1) * (m + 1); Â
    // Finding sum of first n integers     // of AP in case of Row major matrix     int rowmajorSum = sn(n, an); Â
    // Finding nth element in AP     // in case of Row major matrix     an = 1 + (n - 1) * (n + 1); Â
    // Finding sum of first n integers     // of AP in case of Column major matrix     int colmajorSum = sn(n, an); Â
    return rowmajorSum + colmajorSum; } Â
// Driven Program int main() { Â Â Â Â int N = 3, M = 3; Â Â Â Â cout << trace(N, M) << endl; Â Â Â Â return 0; } |
Java
// Java program to find trace of matrix formed // by adding Row-major and Column-major order // of same matrix import java.io.*; Â
public class GFG { Â
    // Return sum of first n integers of an AP     static int sn( int n, int an)     {         return (n * (1 + an)) / 2;     } Â
    // Return the trace of sum of row-major matrix     // and column-major matrix     static int trace( int n, int m)     {         // Finding nth element in         // AP in case of Row major matrix.         int an = 1 + (n - 1) * (m + 1); Â
        // Finding sum of first n integers         // of AP in case of Row major matrix         int rowmajorSum = sn(n, an); Â
        // Finding nth element in AP         // in case of Row major matrix         an = 1 + (n - 1) * (n + 1); Â
        // Finding sum of first n integers         // of AP in case of Column major matrix         int colmajorSum = sn(n, an); Â
        return rowmajorSum + colmajorSum;     } Â
    // Driven Program     static public void main(String[] args)     {         int N = 3, M = 3;         System. out .println(trace(N, M));     } } Â
// This code is contributed by vt_m. |
Python3
# Python3 program to find trace # of matrix formed by adding # Row-major and Column-major # order of same matrix Â
# Return sum of first n # integers of an AP def sn(n, an): Â Â Â Â return (n * ( 1 + an)) / 2 ; Â
# Return the trace of sum # of row-major matrix # and column-major matrix def trace(n, m):          # Finding nth element     # in AP in case of     # Row major matrix.     an = 1 + (n - 1 ) * (m + 1 );          # Finding sum of first     # n integers of AP in     # case of Row major matrix     rowmajorSum = sn(n, an);          # Finding nth element in AP     # in case of Row major matrix     an = 1 + (n - 1 ) * (n + 1 );          # Finding sum of first n     # integers of AP in case     # of Column major matrix     colmajorSum = sn(n, an);          return int (rowmajorSum +                colmajorSum);      # Driver Code N = 3 ; M = 3 ; print (trace(N, M)); Â
# This code is contributed mits |
C#
// C# program to find trace of matrix formed // by adding Row-major and Column-major order // of same matrix using System; Â
public class GFG { Â
    // Return sum of first n integers of an AP     static int sn( int n, int an)     {         return (n * (1 + an)) / 2;     } Â
    // Return the trace of sum of row-major matrix     // and column-major matrix     static int trace( int n, int m)     {         // Finding nth element in         // AP in case of Row major matrix.         int an = 1 + (n - 1) * (m + 1); Â
        // Finding sum of first n integers         // of AP in case of Row major matrix         int rowmajorSum = sn(n, an); Â
        // Finding nth element in AP         // in case of Row major matrix         an = 1 + (n - 1) * (n + 1); Â
        // Finding sum of first n integers         // of AP in case of Column major matrix         int colmajorSum = sn(n, an); Â
        return rowmajorSum + colmajorSum;     } Â
    // Driven Program     static public void Main()     {         int N = 3, M = 3;         Console.WriteLine(trace(N, M));     } } Â
// This code is contributed by vt_m. |
PHP
<?php // PHP program to find trace of matrix formed // by adding Row-major and Column-major order // of same matrix Â
// Return sum of first n integers of an AP function sn( $n , $an ) { Â Â Â Â return ( $n * (1 + $an )) / 2; } Â
// Return the trace of sum // of row-major matrix // and column-major matrix function trace( $n , $m ) {          // Finding nth element in     // AP in case of Row major matrix.     $an = 1 + ( $n - 1) * ( $m + 1); Â
    // Finding sum of first n integers     // of AP in case of Row major matrix     $rowmajorSum = sn( $n , $an ); Â
    // Finding nth element in AP     // in case of Row major matrix     $an = 1 + ( $n - 1) * ( $n + 1); Â
    // Finding sum of first n integers     // of AP in case of Column major matrix     $colmajorSum = sn( $n , $an ); Â
    return $rowmajorSum + $colmajorSum ; }          // Driver Code     $N = 3;     $M = 3;     echo trace( $N , $M ), "\n" ; Â
// This code is contributed ajit ?> |
Javascript
<script> Â
// Javascript program to find trace of matrix formed // by adding Row-major and Column-major order // of same matrix Â
    // Return sum of first n integers of an AP     function sn(n,an)     {         return (n * (1 + an)) / 2;     } Â
    // Return the trace of sum of row-major matrix     // and column-major matrix     function trace(n,m)     {         // Finding nth element in         // AP in case of Row major matrix.         let an = 1 + (n - 1) * (m + 1); Â
        // Finding sum of first n integers         // of AP in case of Row major matrix         let rowmajorSum = sn(n, an); Â
        // Finding nth element in AP         // in case of Row major matrix         an = 1 + (n - 1) * (n + 1); Â
        // Finding sum of first n integers         // of AP in case of Column major matrix         let colmajorSum = sn(n, an); Â
        return rowmajorSum + colmajorSum;     } Â
    // Driven Program              let N = 3, M = 3;         document.write(trace(N, M)); Â
// This code is contributed // by sravan kumar Gottumukkala Â
</script> |
30
 Time Complexity: O(1), as we are not using any loops.
Auxiliary Space: O(1), as we are not using any extra space.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!