Magic Square Generator
Generate magic squares of any odd size (3×3 to 11×11).
About this tool
A magic square is a classic piece of recreational mathematics: a square grid filled with distinct numbers arranged so that every row, column, and diagonal adds up to the same total, known as the magic constant. This generator builds a valid magic square instantly for any odd order, sparing you the trial and error of constructing one by hand.
Just choose an odd size from 3x3 up to 11x11 and generate the square; every row, column, and main diagonal will add up to exactly the same total. It is handy for teaching number patterns, designing puzzles, exploring recreational math, or testing a programming exercise.
As a tip, odd-order magic squares are constructed with the Siamese method, and the magic constant grows steadily as the size increases. Everything runs locally in your browser, so no data ever leaves your device.
Frequently Asked Questions
Code Implementation
def generate_odd_magic_square(n):
"""Siamese (De la Loubère) method for odd n."""
grid = [[0] * n for _ in range(n)]
row, col = 0, n // 2
for num in range(1, n * n + 1):
grid[row][col] = num
next_row = (row - 1) % n
next_col = (col + 1) % n
if grid[next_row][next_col] != 0:
row = (row + 1) % n
else:
row, col = next_row, next_col
return grid
def magic_constant(n):
return n * (n * n + 1) // 2
for n in [3, 5]:
sq = generate_odd_magic_square(n)
print(f"\n{n}x{n} Magic Square (constant={magic_constant(n)}):")
for row in sq:
print(" ".join(f"{v:3}" for v in row))Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.