Magic

Generate magic squares for any odd side length:

#!/usr/bin/env python3
import sys
def magic_constant(n):
    return n * (n * n + 1) // 2
def magic_square(n):
    square = [[0] * n for _ in range(n)]
    num = 1
    i, j = 0, n // 2
    while num <= n * n:
        square[i][j] = num
        num += 1
        new_i = (i - 1) % n
        new_j = (j + 1) % n
        if square[new_i][new_j]:
            i = (i + 1) % n
        else:
            i, j = new_i, new_j
    return square
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
square = magic_square(n)
width = len(str(n * n))
print(f"Magic constant for n={n}: {magic_constant(n)}\n")
for row in square:
    print(" ".join(f"{x:>{width}}" for x in row))

Unknown's avatar

About Linuxgal

Need a spiritual home? Consider joining us at Mary Queen of the Universe Latter-day Buddhislamic Free Will Christian UFO Synagogue of Vishnu
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment