Function Repository Resource:

MagicSquare

Source Notebook

Get a magic square for any dimension

Contributed by: Onkar Singh

ResourceFunction["MagicSquare"][n]

gives a magic square of dimension n.

Details

A magic square is an n×n square array of the numbers 1,2,,n2, arranged so that the sum of the numbers in a row, column or main diagonal is constant.

Examples

Basic Examples (1) 

Get a 3×3 magic square (also known as the Lo Shu square):

In[1]:=
ResourceFunction["MagicSquare"][3]
Out[1]=

Scope (2) 

Generate a 6×6 magic square:

In[2]:=
ResourceFunction["MagicSquare"][6] // MatrixForm
Out[2]=

An 8×8 magic square:

In[3]:=
ResourceFunction["MagicSquare"][8] // MatrixForm
Out[3]=

Properties and Relations (2) 

Visualize the sums within a 5×5 magic square:

In[4]:=
With[{m = ResourceFunction["MagicSquare"][5], n = 5},
 Graphics[{
       Table[{Line[{{0, i}, {n, i}}], Line[{{i, 0}, {i, n}}]}, {i, 0, n}],
       Table[
    Text[Style[ToString[m[[i, j]]], 16], {j - .5, (n - i + 1) - .5}], {i, n}, {j, n}], Red, Table[{Arrow[{{1/2, i - 1/2}, {n - 1/2, i - 1/2}}], Arrow[{{i - 1/2, n - 1/2}, {i - 1/2, 1/2}}]}, {i, n}], Arrow[{{1/2, n - 1/2}, {n - 1/2, 1/2}}], Arrow[{{1/2, 1/2}, {n - 1/2, n - 1/2}}]
     }]]
Out[4]=

Check that the row, column, main diagonal and antidiagonal sums all agree, and are equal to the magic constant:

In[5]:=
Total[ResourceFunction["MagicSquare"][5], {1}]
Out[5]=
In[6]:=
Total[ResourceFunction["MagicSquare"][5], {2}]
Out[6]=
In[7]:=
Tr[ResourceFunction["MagicSquare"][5]]
Out[7]=
In[8]:=
Tr[Reverse[ResourceFunction["MagicSquare"][5]]]
Out[8]=
In[9]:=
With[{n = 5}, (n^2 + 1)/2 n]
Out[9]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.1.0 – 24 August 2021
  • 1.0.0 – 20 February 2019

Related Resources

License Information