A conventional magic square of order n is a square filled with the numbers 1 through n*n such that the sum of the rows, columns and diagonals is the same. Each number in the square must be distinct, and thus every number is used exactly once.
Surprisingly, it is very easy to create magic squares when n is odd. Magic squares of even n also exist, but creating them is comparatively more difficult.
What follows is a program to create odd magic squares of any (reasonable) size. Give it a try... enter an odd number (3 to 49) and the program should reply with a magic square.
Animation speed: 1.0x
The program uses an extraordinarily simple algorithm (which you might be able to understand in its entirety just by looking at the animation above). It is called the Siamese Method.
- We start at top row, middle column and write "1" in that cell.
We move diagonally from the current cell towards top right direction. There are 5 possibilities for this movement.
a. We reach an empty cell. In this case, we write the next number in the empty cell and it becomes our new current cell. Repeat step 2.
b. We reach an occupied cell. In this case, we move to the cell directly below the current cell (which will be empty). We write the next number into this cell, and it becomes the current cell. Repeat step 2.
c. We fall out of the square at the top (not the corner). In this case, we move to the cell on the last row on the next column and write the next number. Repeat step 2.
d. We fall out of the square at the right (not the corner). We move to the first column of the row above and write the next number. Repeat step 2.
e. We fall out at the top right corner. In this case, we move to the cell below the current cell and write the next number. Repeat step 2.
An even easier way to understand the algorithm is to imagine repeating copies of our square in both the x and y directions. In that case, the rules become even simpler.
- Start at middle of top row and write 1 (all copies of the square also get a 1 in the same place).
- Move to the cell towards the top right. If top-right cell is occupied, move one cell down instead. Write the next number (in the same cell in all copies) and repeat this step.
Much easier than remembering 5 different steps.