# Function to check if the matrix is a magic square
def is_magic_square(matrix):
size = len(matrix)
sum_diagonal1 = 0
sum_diagonal2 = 0
# Calculate the sum of the primary diagonal
for i in range(size):
sum_diagonal1 += matrix[i][i]
# Calculate the sum of the secondary diagonal
for i in range(size):
sum_diagonal2 += matrix[i][size - i - 1]
# If the two diagonals don't have the same sum, it's not a magic square
if sum_diagonal1 != sum_diagonal2:
return False
# Check sums of each row and column
for i in range(size):
sum_row = 0
sum_col = 0
for j in range(size):
sum_row += matrix[i][j] # Sum of the current row
sum_col += matrix[j][i] # Sum of the current column
# If any row or column sum is not equal to the diagonal sum, it's not a magic square
if sum_row != sum_diagonal1 or sum_col != sum_diagonal1:
return False
# If all checks pass, it's a magic square
return True
matrix = [
[8, 3, 4],
[1, 5, 9],
[6, 7, 2]
]
if is_magic_square(matrix):
print("The given matrix is a magic square.")
else:
print("The given matrix is NOT a magic square.")
"""
run:
The given matrix is a magic square.
"""