Educatifu
Open menu

Matrix Diagonal Sum

Mediummatrix

Sum the elements on both diagonals of a square matrix. If the matrix has an odd size, the centre element lies on both diagonals — count it only once.

Input

Line 1: an integer n. The next n lines each contain n integers (the matrix rows).

Output

The sum of the primary diagonal plus the secondary diagonal, counting the centre once.

Examples

Example 1

Input
3
1 2 3
4 5 6
7 8 9
Output
25

Primary 1+5+9, secondary 3+5+7, minus the centre 5 → 25.

Example 2

Input
2
1 2
3 4
Output
10

No centre overlap: (1+4) + (2+3) = 10.

Example 3

Input
1
5
Output
5

A single element is the whole of both diagonals — 5.

Constraints

  • 1 <= n <= 100
  • -10^4 <= each element <= 10^4

Hints

Reveal hint 1

The primary diagonal is element (i, i); the secondary diagonal is element (i, n-1-i).

Reveal hint 2

When n is odd, the middle element (i == n-1-i) is on both — add it once, not twice.

Reference solution (spoiler — try it yourself first)

Approach

For each row i add m[i][i] and m[i][n-1-i]; when i == n-1-i (the centre) subtract one copy so it counts once.

import sys
lines = [l for l in sys.stdin.read().split('\n') if l.strip() != '']
n = int(lines[0])
m = [list(map(int, lines[1 + i].split())) for i in range(n)]
s = 0
for i in range(n):
    s += m[i][i] + m[i][n - 1 - i]
    if i == n - 1 - i:
        s -= m[i][i]
print(s)

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation