A magic square is an n×n matrix where:
- Each cell contains a unique integer from 1 to n²
- The sum of each row, each column, and both diagonals is the same
This algorithm works for odd values of n.
1 in the middle column of the first row.
def generate_magic_square(n):
if n % 2 == 0:
raise ValueError("Magic square generation only works for odd n.")
square = [[0] * n for _ in range(n)]
num = 1
row, col = 0, n // 2 # Step A
while num <= n * n:
square[row][col] = num
num += 1
next_row = (row - 1) % n # Step B + wrap
next_col = (col - 1) % n
if square[next_row][next_col] != 0: # Step C
row = (row + 1) % n
else:
row, col = next_row, next_col
return square
# Display the magic square
n = int(input("Enter an odd number n: "))
magic = generate_magic_square(n)
print("\nMagic Square:")
for row in magic:
print(row)
Magic Square:
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]
Each number from 1 to n² is placed according to the diagonal rule.
If the diagonal cell is occupied or out of bounds, the algorithm adjusts by moving down or wrapping around.
The final matrix satisfies the magic condition: all rows, columns, and diagonals have equal sums.