📅  最后修改于: 2023-12-03 15:37:15.679000             🧑  作者: Mango
This is a question from the 2017 ISRO Computer Science examination. The problem statement is as follows:
A magic square of order n is an arrangement of the integers from 1 to n^2 in an n x n matrix, with each integer occurring exactly once, and such that the sum of the entries of any row, any column, or any diagonal is the same. Given an integer n, your task is to construct a magic square of order n.
The input contains a single integer n
The output contains n lines, each having n space separated integers representing the magic square.
3
8 1 6
3 5 7
4 9 2
The above matrix is a 3 x 3 magic square with a sum of 15 in each row, column, and diagonal.
One possible algorithm for generating a magic square of order n is as follows:
The algorithm can be implemented easily in Python. Here's the code:
def generate_magic_square(n):
# Initialize the matrix with zeros
magic_square = [[0 for _ in range(n)] for _ in range(n)]
# Set the initial cell indices to the center of the first row and first column
i, j = 0, n // 2
for num in range(1, n*n+1):
magic_square[i][j] = num
# Move to the next cell
i -= 1
j += 1
# If the cell is out of bounds, wrap around to the opposite side of the matrix
if i < 0 and j < n:
i = n-1
elif j == n and i >= 0:
j = 0
elif i < 0 and j == n:
i, j = n-2, 1
elif magic_square[i][j] != 0:
i, j = i+1, j-2
# Print the magic square
for row in magic_square:
print(' '.join(map(str, row)))
The generate_magic_square function takes an integer n as input and prints the magic square of order n. Here's how you can use the function:
n = int(input())
generate_magic_square(n)
In this article, we have discussed one possible algorithm for generating a magic square of order n and provided an implementation in Python. The algorithm is simple and can be easily understood and modified to meet different requirements.