Skip to main content

Magic Square Solver

Complete a magic square so every row, column, and diagonal share one sum.

A magic square fills an n by n grid with the distinct numbers 1 to n squared so that every row, every column, and both main diagonals add up to the same total, the magic constant. Type the numbers you already know into the grid and leave the rest blank, then solve. A larger empty square has many magic squares, so fill in a few numbers to pin down the one you want.

How it works

The magic constant for an n by n square is n times n squared plus one, divided by two: 15 for 3 by 3, 34 for 4 by 4, and 65 for 5 by 5. The solver places the remaining numbers one cell at a time, in reading order, rejecting any choice that pushes a row, column, or diagonal past the magic constant, which keeps the search quick.

With few or no given numbers a 5 by 5 square has an enormous number of solutions, so the solver caps its effort and asks for more givens rather than hanging. Add a handful of known cells and it returns at once.