魔方陣ジェネレーター
奇数サイズ(3×3〜11×11)の魔方陣を生成します。
よくある質問
コード実装
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.