These are called magic squares. A magic square of order n (integers from 1 to n*n) has only one possible sum: (n*n+1)*n/2.
Odd and even order squares must be constructed by different approaches. For odd orders, the most common algorithm is a recursive scheme devised by de la Loubere about 300 years ago. For even orders, one procedure is the Devedec algorithm, which treats even orders not divisible by 4 slightly differently from those which are divisible by 4 (doubly even).
For squares with odd-length sides, the following algorithm builds a magic square:
Put 1 in the middle box in the upper row. From then on, if it's possible to put the next number one box diagonally up and to the right (wrapping around if the edge of the grid is reached), do so, otherwise, put it directly below the last one.
See archive entry knight.tour for magic squares that are knight's tours.
To get a 4x4 square, write the numbers in order across each row, filling the square...
- then use the following pattern as a mask
- . X X . X . . X X . . X . X X .
- n*n+1). For the 4x4 you get
- 1 15 14 4 12 6 7 9 8 10 11 5 13 3 2 16
For n even (n>4):
Make an initial magic square by writing an n/2 magic square four times (the same one each time). Now, although this square adds up right we have the numbers 1 to n*n/4 written four times each. To fix this, simply add to it n*n/4 times one of the following magic squares:
if n/2 is odd (example: n/2=7),
if n/2 is even (example: n/2=4),