Magic

Generate magic squares for any odd side length with #Python

#!/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  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 Reply