1、 用程序实现幻方。 实现功能:出10阶及10阶以内的幻方 输入:无 输出:n阶幻方 解题思路:根据幻方类型(奇数阶、4k阶、4k+2阶)进行程序设计。
时间: 2024-03-06 19:46:14 浏览: 72
幻方程序实现
以下是 Python 代码实现 n 阶幻方,包括奇数阶幻方和4k阶、4k+2阶幻方:
```python
def generate_magic_square(n):
if n % 2 == 1: # 奇数阶幻方
magic_square = [[0 for x in range(n)] for y in range(n)]
row, col = 0, n // 2
for i in range(1, n * n + 1):
magic_square[row][col] = i
if i % n == 0:
row += 1
else:
row = (row - 1 + n) % n
col = (col + 1) % n
return magic_square
elif n % 4 == 0: # 4k阶幻方
magic_square = [[0 for x in range(n)] for y in range(n)]
for i in range(n):
for j in range(n):
if i % 4 == j % 4 or (i + j) % 4 == 3:
magic_square[i][j] = (n * i + j + 1)
else:
magic_square[i][j] = (n * n - n * i + j)
return magic_square
else: # 4k+2阶幻方
k = n // 2
M = generate_magic_square(k)
magic_square = [[0 for x in range(n)] for y in range(n)]
for i in range(k):
for j in range(k):
magic_square[i][j] = M[i][j]
magic_square[i][j + k] = M[i][j] + 2 * k * k
magic_square[i + k][j] = M[i][j] + 3 * k * k
magic_square[i + k][j + k] = M[i][j] + k * k
if n == 2 * k:
for i in range(k):
magic_square[i][k - 1], magic_square[i + k][k - 1] = \
magic_square[i + k][k - 1], magic_square[i][k - 1]
else:
r = k // 2
magic_square[r][r], magic_square[r + k][r] = \
magic_square[r + k][r], magic_square[r][r]
magic_square[r][r + k], magic_square[r + k][r + k] = \
magic_square[r + k][r + k], magic_square[r][r + k]
return magic_square
n = 10 # 需要生成的幻方阶数
if n <= 10:
magic_square = generate_magic_square(n)
for row in magic_square:
print(row)
else:
print('暂不支持生成超过10阶幻方!')
```
这段代码中,`generate_magic_square` 函数接受一个整数 n,返回一个 n 阶幻方的二维数组。如果 n 是奇数,就使用经典的方法生成奇数阶幻方;如果 n 是4k阶或4k+2阶,就使用 LUX 方法生成幻方。最后,如果需要生成的幻方阶数超过10阶,就输出错误信息。
阅读全文