Saturday, March 31, 2012

Magic Squares - Explained


Magic Squares - explained
=========================

Here is a 3 x 3 magic square.



- the rows add up to T = 15.
- the columns add up to T
- the diagonals add up to T

Here's how to do it:

x 1 x ----- x 1 x   -----  x 1 x
x x x  ----- x x x  ----- 3 x x
x x x  ----- x x 2  ----- x x 2


x 1 x  -----  x 1 x ----- x 1 6
3 x x  ----- 3 5 x ----- 3 5 x
4 x 2  ----- 4 x 2  ----- 4 x 2


x 1 6  ----- 8 1 6  -----  8 1 6
3 5 7  ----- 3 5 7  ----- 3 5 7
4 x 2  ----- 4 x 2  ----- 4 9 2


1. Start from top row middle column with S=1, S is the starting value.
2. Add 2,3,4,5,6,7,8,9 diagonally, that means try to go UP then RGIHT.
3. If UP is blocked, go to Right column, and fill the bottom row. eg. like filling "2".
4. If RIGHT is blocked, go to the LEFT most column of one row above, eg like filling "3".
5. Since this is a 3x3 square, after 3 numbers, then fill the next number just one row DOWN.
eg like filling in "4".
6. Repeat from step 3.

To generalize to N x N magic squares (MS), where N is ODD,
- in step 5 above, after filling every N numbers, move down exactly ONE row.
- the movement of UP -> RIGHT, that is diagonally, is same for all N x N magic squares.
- the relationship between the starting number S and the total number T is like this.
for 3x3 MS:   T / 3 - 4 = S       , 3 x 1 + 1 = 4
for 5x5 MS:   T / 5 - 12 = S      , 5 x 2 + 2 = 12
for 7x7 MS:   T / 7 - 24 = S      , 7 x 3 + 3 = 24
for 9x9 MS:   T / 9 - 40 = S      , 9 x 4 + 4 = 40
for NxN MS:   T / N - K  = S      , N x (N-1)/2 + (N-1)/2 = N*N/2 - 1/2

- The sum of all rows or columns or diagonal T, must be divisible by N.
- For any N, the minumum S is 1.
- For any N, the constant K = N*N/2 - 1/2
- For any N, the minimum T is when S = 1,
   so Tmin = (1 + N*N/2 - 1/2 ) * N

No comments: