# JavaScript Program to Efficiently compute sums of diagonals of a matrix

We are going to write a program in JavaScript that efficiently computes the sum of the diagonals of a matrix. To do this, we will utilize a loop structure that iterates through the matrix and adds the elements located at the positions that correspond to the diagonals. By taking advantage of the mathematical properties of a matrix, we can minimize the amount of computation required to find the sum of the diagonals. With this approach, we will be able to handle matrices of various sizes in a computationally efficient manner.

## Approach

• To compute the sum of diagonals of a matrix, we need to add up the values of the elements present on the main diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left)

• A two-loop approach can be used where one loop iterates through the rows and the second loop iterates through the columns to access the elements on the diagonals.

• We can keep two variables to store the sum of elements on the main and secondary diagonals respectively.

• To access the elements on the main diagonal, we need to add the current row and column indices, whereas for the secondary diagonal, we need to subtract the column index from the row index.

• Finally, we return the sum of both variables as the result, which would give us the sum of elements on both diagonals of the matrix.

## Example

Here is an example of a JavaScript program that efficiently computes the sum of the diagonals of a matrix −

function diagonalSum(matrix) {
let sum = 0;
let n = matrix.length;

for (let i = 0; i < n; i++) {
sum += matrix[i][i];
sum += matrix[i][n - i - 1];
}

if (n % 2 !== 0) {
let mid = Math.floor(n / 2);
sum -= matrix[mid][mid];
}

return sum;
}
const matrix = [[1, 2, 3],[4, 5, 6], [7, 8, 9]];
console.log(diagonalSum(matrix));


## Explanation

• Initialize a variable sum to store the sum of the diagonals and a variable n to store the number of rows in the matrix.

• Use a for loop to iterate through the matrix, adding the values of the diagonals to sum. For each iteration i, we add the value of the main diagonal matrix[i][i] and the anti-diagonal matrix[i][n - i - 1].

• If the number of rows in the matrix is odd, we subtract the middle value matrix[mid][mid] (where mid is the middle row index, calculated using Math.floor(n / 2)) as it would have been added twice.

• Return the value of sum.

This algorithm has a time complexity of O(n), making it an efficient solution for computing the sum of the diagonals of a matrix.

Updated on: 13-Mar-2023

132 Views 