AlgoVerse

Magic square

Fill an n×n grid (n odd) with 1 to n² so every row, column and diagonal has the same sum, by the Siamese method: one up, one right.

In a magic square all rows, columns and both diagonals have the same sum: n(n² + 1) / 2.

Read the full explanation ↓
Input:
n=3PDF export

The 3×3 square (the Lo Shu): every row, column and diagonal adds up to 15.

  1. def magic_square(n):
  2. if n % 2 == 0:
  3. return None
  4. square = [[0] * n for _ in range(n)]
  5. r, c = 0, n // 2
  6. for k in range(1, n * n + 1):
  7. square[r][c] = k
  8. nr, nc = (r - 1) % n, (c + 1) % n # up and to the right, wrapping around
  9. if square[nr][nc] != 0:
  10. nr, nc = (r + 1) % n, c
  11. r, c = nr, nc
  12. return square

Invariant: The numbers run along wrapped diagonals, n per diagonal; then one step down starts the next diagonal.

Start

k—
r—
c—

The table is still empty.

Local variables

n3

Orange = changed in this step

Call stack

  1. magic_square()line 1
Step 1 of 54
Black = put · Orange = key stepput: 0/9 · blocked: 0/3
    Explanation

    The idea

    In a magic square all rows, columns and both diagonals have the same sum: n(n² + 1) / 2.

    The Siamese method (n odd)

    1. Put 1 in the middle of the top row.
    2. Put each next number one up and one right; if you leave the grid, come back on the other side (the grid wraps around).
    3. If that square is taken, put the number one below the previous one instead.

    The numbers run along wrapped diagonals; each diagonal holds exactly n squares, and every row and column gets exactly one number from each group of n, which is why the sums agree.

    What to watch in the trace

    • The table is the square; notice that after every n numbers there is one step down.