Find the product of sum of two diagonals of a square Matrix
Last Updated :
10 Aug, 2022
Given a square matrix mat consisting of integers of size NxN, the task is to calculate the product between the sums of its diagonal.
Examples:
Input: mat[][] = {{5, 8, 1},
{5, 10, 3},
{-6, 17, -9}}
Output: 30
Sum of primary diagonal = 5 + 10 + (-9) = 6.
Sum of secondary diagonal = 1 + 10 + (-6) = 5.
Product = 6 * 5 = 30.
Input: mat[][] = {{22, -8, 11},
{55, 87, -1},
{-61, 69, 19}}
Output: 4736
Naive approach: Traverse the entire matrix and find the diagonal elements. Calculate the sums across the two diagonals of a square matrix. Then, just take the product of the two sums obtained.
Time complexity: O(N2)
Naive approach: Traverse just the diagonal elements instead of the entire matrix by observing the pattern in the indices of the diagonal elements.
Below is the implementation of this approach:
CPP
#include <bits/stdc++.h>
using namespace std;
long long product(vector<vector< int >> &mat, int n)
{
long long d1 = 0, d2 = 0;
for ( int i = 0; i < n; i++)
{
d1 += mat[i][i];
d2 += mat[i][n - i - 1];
}
return 1LL * d1 * d2;
}
int main()
{
vector<vector< int >> mat = {{ 5, 8, 1},
{ 5, 10, 3},
{ -6, 17, -9}};
int n = mat.size();
cout << product(mat, n);
return 0;
}
|
Java
class GFG{
static long product( int [][]mat, int n)
{
long d1 = 0 , d2 = 0 ;
for ( int i = 0 ; i < n; i++)
{
d1 += mat[i][i];
d2 += mat[i][n - i - 1 ];
}
return 1L * d1 * d2;
}
public static void main(String[] args)
{
int [][]mat = {{ 5 , 8 , 1 },
{ 5 , 10 , 3 },
{ - 6 , 17 , - 9 }};
int n = mat.length;
System.out.print(product(mat, n));
}
}
|
Python3
def product(mat,n):
d1 = 0
d2 = 0
for i in range (n):
d1 + = mat[i][i]
d2 + = mat[i][n - i - 1 ]
return d1 * d2
if __name__ = = '__main__' :
mat = [[ 5 , 8 , 1 ],
[ 5 , 10 , 3 ],
[ - 6 , 17 , - 9 ]]
n = len (mat)
print (product(mat, n))
|
C#
using System;
class GFG{
static long product( int [,]mat, int n)
{
long d1 = 0, d2 = 0;
for ( int i = 0; i < n; i++)
{
d1 += mat[i, i];
d2 += mat[i, n - i - 1];
}
return 1L * d1 * d2;
}
public static void Main(String[] args)
{
int [,]mat = {{ 5, 8, 1},
{ 5, 10, 3},
{ -6, 17, -9}};
int n = mat.GetLength(0);
Console.Write(product(mat, n));
}
}
|
Javascript
<script>
function product(mat, n)
{
let d1 = 0, d2 = 0;
for (let i = 0; i < n; i++)
{
d1 += mat[i][i];
d2 += mat[i][n - i - 1];
}
return d1 * d2;
}
let mat = [[ 5, 8, 1],
[ 5, 10, 3],
[ -6, 17, -9]];
let n = mat.length;
document.write(product(mat, n));
</script>
|
Time complexity: O(N)
Auxiliary Space: O(1) because using constant variables
Share your thoughts in the comments
Please Login to comment...