MAGIC SQUARES dialy qs

can u provide me with the solution to this qs??

I cannot provide you the solution but I can help you to understand the concept behind this problem.

A magic square is a 2D square matrix of n rows and n columns with three properties:

  1. Each element is a distinct number.
  2. The sum of all the elements in each row, column or diagonal is same.
  3. The sum is given by n(n^2+1)/2
    Example:

Magic Square of size 3

2 7 6
9 5 1
4 3 8
Sum in each row & each column = 3*(3^2+1)/2 = 15

Magic Square of size 5

9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17
Sum in each row & each column = 5*(5^2+1)/2 = 65

Magic Square of size 7

20 12 4 45 37 29 28
11 3 44 36 35 27 19
2 43 42 34 26 18 10
49 41 33 25 17 9 1
40 32 24 16 8 7 48
31 23 15 14 6 47 39
22 21 13 5 46 38 30
Sum in each row & each column = 7*(7^2+1)/2 = 175

There is a pattern you can see common in all these matrices:

  1. The first element is at the position (n/2 , n-1). Let these positions be (i, j), where i=n/2 and j=n-1

  2. Now consider row and columns as two circular arrays.

  3. So, the next element would be placed at a position (i-1,j+1) i.e. row is decremented by 1 and column is incremented by 1.

Now, while writing the code you have to keep three conditions in mind:

  1. The position of next number is calculated by decrementing row number of previous number by 1, and incrementing the column number of previous number by 1. At any time, if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the calculated column position becomes n, it will wrap around to 0.

  2. If the magic square already contains a number at the calculated position, calculated column position will be decremented by 2, and calculated row position will be incremented by 1. {This is the car for number 4 in first example. }

  3. If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2). {This is case of number 7 in first example of order 3X3.}

Hope it will help you understand the concept. If you still have doubts, feel free to ask.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.