0

Let n=5, then for matrix

1  2  3  4  5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8 
13 12 11 10 9

then sum of diagonal elements is:

=1+17+25+21+9+5+19+23+13

Sum for n=15?

One way is to make the spiral matrix and then by a loop, we get the answer, but its time and space complexity is large.

Like this https://www.geeksforgeeks.org/sum-diagonals-spiral-odd-order-square-matrix/ but the problem here starts 1 from the center.

Badhan Sen
  • 617
  • 1
  • 7
  • 18
ajay kumar
  • 11
  • 3
  • If they start from the center, you can see it as being a similar problem, the value `M(i,j)` in a matrix starting from center being `n² - M(i,j)` in the matrix starting from an extremity point. – m.raynal Apr 02 '19 at 13:04

2 Answers2

2

Consider the outer "shell" of the matrix. The sum of the values at the four vertices, given a size of n (5 in your example) and a starting value of s (1 in your example) is

s + (s + (n-1)) + (s + (n-1)*2) + (s + (n-1)*3) = 4*s + (n - 1)*6

The same applies to the inner values, once updated n and s:

s = s + 4 * (n - 1)
n = n - 2

If n becomes less then 2, well, either we have the central element or nothing (n is even).

Bob__
  • 12,361
  • 3
  • 28
  • 42
0

Based on Bob_'s answer, Here is a recursive code in CPP as requested by OP

int shellcalc(int n,int s){
    if(n==1)
        return s;
    else if(n==0)
        return 0;
    else
    {
        int sum=4*s+(n-1)*6;
        int snew=s+4*(n-1);
        int nnew=n-2;
        return sum+shellcalc(nnew,snew);
    }
}

try it out here https://rextester.com/FLJD46264
Python - https://rextester.com/MDMV32855

Mohit Burkule
  • 136
  • 1
  • 6