Intriguing symmetries are uncovered regarding all magic squares of orders 3, 4, and 5, with 1, 880, and 275,305,224 distinct configurations, respectively. In analogy with the travelling salesman problem, the distributions of the total topological distances of the paths travelled by passing through all the vertices (matrix elements) only once and spanning all elements of the matrix are analyzed. Symmetries are found to characterize the distributions of the total topological distances in these instances. These results raise open questions about the symmetries found in higher-order magic squares and the formulation of their minimum and maximum total path lengths.
Magic squares have captivated mathematicians, historians, and enthusiasts for centuries with their intricate patterns and inherent mathematical properties [1, 2, 7, 12, 23, 19, 3]. The concept of magic squares can be traced back thousands of years to ancient civilizations such as China [4], India [24], and the Middle East [24]. Over the centuries, magic squares have captured the imagination of mathematicians including, for example, the Persian mathematician Abu al-Wafa’al-Buzjani [24] up to Leonard Euler [8]. These intriguing structures are square matrices filled with distinct integers such that they possess a remarkable property, and that is that the sum of any row, column, or main diagonal is equal.
A classic or natural magic square of order \( n \) is an array of distinct positive integers ranging from 1 to \( n^2 \). This arrangement ensures that the sum of any \( n \) numbers in a horizontal, vertical, or main diagonal line consistently equals a specific value known as the magic constant. The mathematical expression for the magic constant is \( M_n = \frac{n}{2} (n^2 + 1) \). We define two subgroups of magic squares that will be explored later in this paper. An \( n \times n \) classic magic square earns the label “associative” when each pair of numbers symmetrically opposite the center sums to \( n^2 + 1 \) [12]. Moreover, a classic magic square earns the designation of a pandiagonal magic square if the sum of all its diagonals, including those derived by “wrapping around” the edges, equals the same magic constant [12].
The number of possible (classic) magic squares of a given dimension explodes very quickly with matrix size [25, 20, 15, 16]. We define an ‘irreducible’ square as one with the smallest denominator of the infinite number of corresponding squares obtained by multiplication with a constant. A \( 3 \times 3 \) magic square has only one possible irreducible arrangement, there are 880 irreducible \( 4 \times 4 \) magic squares, there are 275,305,224 irreducible magic square of size \( 5 \times 5 \), and an estimated \( \alpha \). \( 2.4 \times 10^{110} \) of size \( 10 \times 10 \) [25]. The law determining the number of magic squares of a given type given the matrix size remains unknown and an active area of research [25].
Magic squares, besides their mathematical elegance, aesthetic appeal, and remarkable properties, may also have practical applications. Magic squares have been employed in classical mechanics [21, 17], electrostatics [9, 13, 11, 22], and even quantum mechanics [5, 6].
The representation of magic squares in binary format reveals underlying patterns [10], which may hold potential implications in binary systems within the realm of physics, such as the 2D Ising model [18]. In a recent study by Fahimi [10], the author introduces a method for exploring similarities within magic squares by assigning two distinct colors to the even and odd numbers. This technique encompasses various analyses such as rotation/reflection, Principal Component Analysis (PCA), and Linear Discriminant Analysis (LDA). Initially, the magic squares undergo conversion into their binary format. The subsequent step involves flattening each binary matrix into an \( n^2 \)-dimensional vector, where ‘\( n \)’ denotes the order of the square. Following this transformation, a dimensionality reduction technique, such as PCA, is applied to condense the information into two components, offering a more accessible representation. However, a rigorous mathematical and analytical exploration is necessary as a follow-up to this numerical investigation. This entails tasks like computing covariance matrices and performing eigenvalue decomposition for each binary magic square. Such a comprehensive approach unravels valuable insights into the underlying principles, enriching our comprehension of the intricate dynamics at play in the realm of magic squares.
In the present study, a significant problem at the intersection of two fields—the traveling salesman problem and magic squares—is addressed through computational and numerical methods. Labeling the matrix elements within a magic square as “cities,” the objective for the “traveler” is to move from city 1 to city n\({}^{2}\), where n represents the order of the magic square (with n = 3, 4, and 5 examined in this paper), while simultaneously minimizing the total path length (finding the optimized trajectory) across a substantial number of potential configurations (e.g., 275,305,224 distinct configurations for order-5 magic squares). By examining the “traveling salesman” trajectories from one city to the next, the second objective is to uncover and analyze the inherent symmetrical patterns in these magical arrangements. These tasks, both computationally intensive and novel in scope, provide open questions for future research.
The methodology, implemented in Python, utilizes data handling libraries such as Pandas and NumPy. A portion of the code related to 4\(\mathrm{\times}\)4 magic squares is included in the Appendix, while other codes, including the code for 5\(\mathrm{\times}\)5 magic squares, as well as the results and plots, are included in the supplementary material.
The code begins by loading magic squares from an Excel file and defining coordinates for the cities on the square grid. The loop iterates through each row of the DataFrame containing the magic squares. For each iteration, the code extracts a magic square from the DataFrame and converts it into a list. It then determines the maximum number present in that particular magic square. The next step involves creating a dictionary (“city_mapping”) that associates each number in the magic square with its corresponding city coordinates. The cities dictionary holds the predefined coordinates for each city. Using the created “city_mapping” dictionary, the code generates a path for the traveler by mapping the numbers in the magic square to their respective city coordinates. The resulting “x” and “y” lists contain the coordinates of the traveler’s path.
For each magic square, the trajectory of the traveler is plotted, showcasing the movement between cities with arrows. The distances between consecutive cities are calculated, utilizing the Euclidean distance formula. This distance calculation serves as a fundamental metric for analyzing spatial relationships within the magic square arrangement. The resulting plots visually represent both the trajectory and the calculated distances, offering insight into the symmetry embedded in the magic square structure.
Let us consider a 3\(\mathrm{\times}\)3 magic square. As depicted in Figure 1 (left), we envision a distribution of 9 cities on a 3\(\mathrm{\times}\)3 square lattice whereby each neighboring pair of cities is separated by a unit horizontal or vertical distance. The arrangement of the cities precisely mirrors the arrangement of the numbers within a 3\({}^{rd}\) order magic square, resulting in a magical path for the “travelling salesman”.
All possible inter-pair distances are analyzed for their underlying pattern. For instance, the distance between city 1 and city 2 is \(\mathrm{\sqrt{}}\)(1\({}^{2}\)+2\({}^{2}\))=\(\mathrm{\sqrt{}}\)5, while the distance between city 4 and city 5 is \(\mathrm{\sqrt{}}\)2, and so on. In the particular path depicted in Figure 1 (right), the distances pattern exhibits reflective (\(\sigma\)) symmetry about a mirror plane intersection the plane of the figure vertically between abscissa steps 3 and 4. The total distance of the sum of all paths is approximately 13.77. It is worth clarifying at this point that the paths considered in this study must align with the order of occurrence of consecutive magic numbers and not any arbitrary path. In other words, we adhere to the constraint that moving from, for instance, city 1 to city 5 is not permissible. One might, of course, question the possibility of exploring alternative routes, such as moving from 1 to 5 and then to 9, but such deviations are outside the scope of this initial study and may be the subject of a future investigation.
The complexity of paths in 4\(\mathrm{\times}\)4 magic squares represent a greater challenge in discerning their underlying symmetries in terms of topological distance patterns. Among the 880 order 4 magic squares, it is observed that the maximum and minimum values of the total path distances are approximately 42.76 and 20.31, respectively, while the average total path distance over all 880 magic squares is ca. 33.94.
Figures 2a and 2b illustrate the magic squares with the minimum and maximum total distances, respectively, while 2c displays the distribution of total distances across all 880 magic squares of order 4. Figure 2a represents the shortest pathway for the traveler, while Figure 2b depicts the longest pathway among all 880 routes. Furthermore, the analysis shows that the shortest total trajectory is 20.3, with an average distance of 1.35 between each pair of consecutive cities (as illustrated in Figure 2a and the supplementary material). In contrast, the longest trajectory extends to 42.7, with an average distance of 2.85 between each pair of consecutive cities (as depicted in Figure 2b and the supplementary material). The distribution of total distances across all 880 magic squares of order 4 is presented in Figure 2c.
Within the set of 880 magic squares of order four, 414 display reflective geometric symmetry in their distance patterns. This symmetry is observed around a mirror plane intersecting the figure’s plane vertically at step 7. In the pursuit of understanding the origins of such symmetries, an in-depth exploration of the 880 magic squares with dimensions 4\(\mathrm{\times}\)4 was conducted, leveraging a classification system devised by H. E. Dudeney [7, 14]. These squares were systematically organized into 12 distinct groups based on the patterns formed by the 8 complement pairs, as illustrated in the left panel of Figure 3 (refer to Figure 3a and b). Here, a complement pair denotes two numbers whose sum equals n\({}^{2}\) + 1, where n represents the order of the magic square; in the case of order 4, this sum is 17.
The classification according to Dudeney’s scheme provides a structured framework for deciphering the underlying patterns that contribute to the emergence of these symmetrical arrangements [7, 14]. It is found that all magic squares belonging to group 3, which consists of 48 associative magic squares with symmetrical number placement around the center point, as well as group 6, comprising 304 semi-pandiagonal and simple magic squares with symmetrical number placement across the center line, demonstrate reflexive symmetry in their distance patterns. Figure 3 showcases a selection of examples from these groups. A comprehensive collection of all examples is available as Supplementary Information. Out of the 880 distance patterns, it is important to note that several are redundant. Instead, there are 112 emerging patterns that exhibit repetition, resulting in a total of 768 unique distance patterns. The reader is reminded that each magic square corresponds to a unique trajectory and total distance pattern, given the constraint of having to follow the sequential numbering of the cities. Thus, we have, for example, a total of 880 trajectories for the 4\(\mathrm{\times}\)4 magic squares within which 112 are identical despite being associated distinct magic squares.
The remaining distance patterns, comprising 466 cases (= 880 – 414), exhibit various types of symmetries, including local symmetry, periodicity (translational symmetry), and partial symmetry. Local symmetry (which 252 patterns exhibit this type of symmetry) refers to the presence of symmetric patterns or characteristics within a specific region or subset of the distance pattern. It implies that certain portions of the pattern exhibit mirror-like or rotational symmetry within themselves. Periodicity or translational symmetry refers to the recurrence or repetition of certain patterns or motifs at regular intervals within the distance pattern. It indicates the existence of a periodic structure or arrangement in the pattern. Partial symmetry suggests that the distance pattern possesses symmetrical elements or features, but not all aspects of the pattern exhibit symmetry. It indicates the presence of symmetry in some parts or components of the pattern while other parts may lack symmetry. In the majority of cases, achieving reflexive symmetry, local symmetry, or periodicity can be accomplished by repositioning a few points (1 to 3 points) in the distance pattern of partial symmetry. These classifications are primarily based on qualitative assessment and may exhibit overlap in certain cases. Figure 4 depicts a few examples of different types which are listed in their entirety in the Supplementary Information.
The presence of partial symmetry in distance patterns can be attributed to the specific arrangement of the cities within the square. The topological distances of different pairs of cities introduce variations that disrupt the symmetry embodied in the magic square by construction. The arrangement of cities within the magic square creates complex interdependencies, leading to partial symmetric patterns in the distances between certain pairs of cities. These patterns may arise due to the specific positioning of cities along diagonal lines, within certain quadrants of the square, or other geometric relationships. It is crucial to emphasize that while the city numbers demonstrate symmetry by adhering to the arrangement of numbers within a magic square, the actual distances between cities are governed by geometric considerations and may not necessarily align with the same level of symmetry. This creates an interesting interplay between the overall symmetric structure of the magic square and the partial symmetries observed in the distance patterns. By analyzing and understanding these partial symmetries, further insights into the underlying principles and properties of magic squares and their associated distance patterns can be gained.
Investigating the trajectory patterns and distance symmetries within 5\(\mathrm{\times}\)5 magic squares poses significant computational challenges due to the vast number of distinct magic squares of order 5, which amounts to 275,305,224 [25]. We calculated the total path length and their respective frequencies, of all these squares, as illustrated in Figure 5. The resulting pattern resembles a Gaussian-type distribution, with the maximum frequency of 32,824 occurring at a total path length of approximately 65.89. The minimum, average, median, maximum, and standard deviation of the total path length are 37.47, 65.49, 65.58, 88.04, and 4.64, respectively. Note that, the diagrams in Figure 5 and Figure 7 do not display the exact total path length S and their frequencies. Rather, they show the number of squares with total path lengths that fall within a small interval around S, specifically [S – 0.005, S + 0.005].
Our analysis demonstrates that the distance pattern of the traveler’s path in all 48,544 instances of associative magic squares of order 5 exhibits a remarkable reflexive geometrical symmetry. Additionally, there are 5,848 non-associative 5\(\mathrm{\times}\)5 magic squares exhibiting reflexive path symmetry. This group of squares also features the number 13 at the center, similar to the associative magic squares. Figure 6 illustrates some notable examples of these patterns.
In a 5\(\mathrm{\times}\)5 magic square, any number from 1 to 25 can occupy the center. Therefore, we categorized all magic squares of order 5 into 25 groups, each defined by a specific number in the center. The results for having x in the center are identical to those with (26 – x) in the center. Consequently, we plotted the total path length distribution for the first 13 groups, with center numbers ranging from 1 to 13. Figure 7 illustrates these distributions, with the maximum frequency and average total path length provided in the legend of each plot. As shown, the average total path length across all groups hovers around 64. Notably, in most cases, the smaller the center number, the lower the height of the Gaussian distribution (i.e., the maximum frequency), though there are exceptions.
Assuming the traveling salesman seeks the minimum total path length (MTPL) for each order of magic squares, the following outlines the steps of the shortest trajectory obtained from numerical analysis of all magic squares of orders 3, 4, and 5:
For \(n = 3\) (only possible path): \[\text{TPL} = \left( 2 \times \sqrt{1^2} \right) + \left( 2 \times \sqrt{1^2+1^2} \right) + \left( 4 \times \sqrt{1^2+2^2} \right).\]
For \(n = 4\) (minimum total path length): \[\text{MTPL} = \left( 6 \times \sqrt{1^2} \right) + \left( 8 \times \sqrt{1^2+1^2} \right) + \left( 1 \times \sqrt{3^2} \right).\]
For \(n = 5\) (minimum total path length): \[\text{MTPL} = \left( 10 \times \sqrt{1^2} \right) + \left( 8 \times \sqrt{1^2+1^2} \right) + \left( 4 \times \sqrt{1^2+2^2} \right) + \left( 2 \times \sqrt{2^2+3^2} \right).\]
Even with the results of the shortest trajectories for magic squares of orders 3, 4, and 5, it remains challenging to propose a general formula for predicting the minimum total path length for higher-order magic squares. Additionally, calculating the total path length (TPL) for higher-order squares is computationally intensive; for instance, there are 17,753,889,197,660,635,632 possible magic squares of order 6 [25]. Therefore, developing a mathematical formula to calculate the minimum total path length (MTPL) for any order remains an open problem for future research.
In this study, an analysis of the topological distances of travelling salesman-like trajectories across the 3\(\mathrm{\times}\)3, 4\(\mathrm{\times}\)4, and 5\(\mathrm{\times}\)5 magic squares were investigated. In the smallest case, that of the unique irreducible 3\(\mathrm{\times}\)3 magic square, the lengths of trajectories exhibit clear reflective \(\sigma\)-symmetry.
A classification of 4\(\mathrm{\times}\)4 magic squares into the 12 groups suggested by Dudeney reveals that a significant portion of the magic squares exhibit reflective \(\sigma\)-symmetry in their distance patterns. Reflexive symmetry was observed in all magic squares categorized under Group 3 and Group 6, whereas other groups exhibited characteristics such as local symmetry, translational symmetry, and partial symmetry.
We investigated the total path length of all 5\(\mathrm{\times}\)5 magic squares, analyzing their frequencies and distributions. By classifying the squares into 25 groups, each with the same number at the center, we observed that groups with smaller center numbers tend to have lower maximum frequencies for total path length. Despite this variation, all 25 groups have an average total path length of approximately 64. Additionally, we identified a reflexive \(\sigma\)-symmetry in the distance patterns of both the associative 5\(\mathrm{\times}\)5 magic squares and 5,848 non-associative ones.
Future investigations are needed to explore the generalization of these findings to squares of higher orders. How can a traveling salesman find the shortest trajectory within 6\(\mathrm{\times}\)6 magic squares without considering all possible paths (approximately \(1.7\mathrm{\times}10^{19}\) paths)?
C.F.M. gratefully acknowledges funding from the Natural Sciences and Engineering Research Council of Canada (NSERC) and Mount Saint Vincent University.
The authors have no conflicts of interest to disclose.
The supplementary material accompanying this paper provides all the codes necessary to reproduce the results reported, a comprehensive collection of the trajectory and distance patterns for all magic squares of order 4, and the calculated total path lengths of all order 5 magic squares along with their distribution. It offers a detailed exploration of the symmetries, patterns, and characteristics exhibited by each magic square in terms of the traveler’s path. Supplementary material is available from the corresponding author upon request.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
# Load the magic squares from the Excel file
df = pd.read_excel(“magic_squares.xlsx”, header=None)
# Define the city coordinates
cities = \(\mathrm{\{}\)
1: (-1.5, 1.5),
2: (-0.5, 1.5),
3: (0.5, 1.5),
4: (1.5, 1.5),
5: (-1.5, 0.5),
6: (-0.5, 0.5),
7: (0.5, 0.5),
8: (1.5, 0.5),
9: (-1.5, -0.5),
10: (-0.5, -0.5),
11: (0.5, -0.5),
12: (1.5, -0.5),
13: (-1.5, -1.5),
14: (-0.5, -1.5),
15: (0.5, -1.5),
16: (1.5, -1.5)
\(\mathrm{\}}\)
# Create a folder for saving the plots
folder_path = “Trajectory-Distance plots”
os.makedirs(folder_path, exist_ok=True)
# Calculate and plot the trajectory for each magic square
for i in range(len(df)):
magic_square = df.iloc[i].values.tolist()
# Find the maximum number in the magic square
max_number = max(magic_square)
# Create a dictionary to map numbers to city coordinates
city_mapping = \(\mathrm{\{}\)magic_square[j]: cities[j+1]
for j in range(max_number)\(\mathrm{\}}\)
# Create the path based on the city coordinates
path = [city_mapping[number] for number in range(1, max_number+1)]
x = [coord[0] for coord in path]
y = [coord[1] for coord in path]
# Plot the trajectory with arrows
for j in range(1, max_number):
plt.arrow(x[j-1], y[j-1], x[j]-x[j-1], y[j]-y[j-1], head_width=0.15,
head_length=0.15, fc=’black’, ec=’black’)
plt.title(’City Trajectory’)
plt.xlabel(’X’)
plt.ylabel(’Y’)
plt.grid(True)
plt.savefig(os.path.join(folder_path, f’trajectory_magic_square_\(\mathrm{\{}\)i+1\(\mathrm{\}}\).png’), dpi=300)
plt.close()
# Calculate distances between consecutive cities
distances = []
for j in range(1, max_number):
distance = np.sqrt((x[j] – x[j-1])**2 + (y[j] – y[j-1])**2)
distances.append(distance)
# Plot the distances
plt.plot(distances, marker=’o’, linestyle=’-’, color=’blue’)
plt.title(’Distances between Consecutive Cities’)
plt.xlabel(’Step’)
plt.ylabel(’Distance’)
plt.grid(True)
plt.savefig(os.path.join(folder_path, f’distances_magic_square_\(\mathrm{\{}\)i+1\(\mathrm{\}}\).png’), dpi=300)
plt.close()
plt.show()