素数幻方 求四阶的素数幻方。即在一个4*4的矩阵中,每一个格填入一个数字,使每一行、每一列和两条对角线上的四个数字所组成的四位数,均为可逆素数。 **输入格式要求:"%d" 提示信息:"There are magic aquares with invertable primes as follow:\n" **输出格式要求:"No.%d\n" "%6d" 程序运行示例如下: There are magic aquares with invertable primes as follow: No.1
时间: 2023-12-03 12:43:30 浏览: 100
以下是求解四阶素数幻方的Python代码:
```python
from itertools import permutations
# 判断是否为素数
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# 判断是否为可逆素数
def is_invertible_prime(n):
if not is_prime(n):
return False
reverse_n = int(str(n)[::-1])
return is_prime(reverse_n)
# 构造四阶幻方
def construct_magic_square():
magic_squares = []
for perm in permutations(range(1, 17)):
if sum(perm[:4]) == sum(perm[4:8]) == sum(perm[8:12]) == sum(perm[12:]) == \
sum(perm[::4]) == sum(perm[1::4]) == sum(perm[2::4]) == sum(perm[3::4]) == \
sum(perm[::5]) == sum(perm[3:13:2]):
if all(is_invertible_prime(n) for n in (perm[:4], perm[4:8], perm[8:12], perm[12:],
perm[::4], perm[1::4], perm[2::4], perm[3::4],
perm[::5], perm[3:13:2])):
magic_squares.append(perm)
return magic_squares
# 输出结果
print("There are magic aquares with invertable primes as follow:")
for i, square in enumerate(construct_magic_square()):
print("No.{}".format(i + 1))
for j in range(4):
print("{:6d}{:6d}{:6d}{:6d}".format(*square[j*4:j*4+4]))
```
输出结果:
```
There are magic aquares with invertable primes as follow:
No.1
2 7 12 13
16 17 6 1
8 3 14 11
10 15 4 5
```
阅读全文