Wolfram Research

Function Repository Resource:

MagicSquare

Source Notebook

Get a magic square for odd dimension

Contributed by: Onkar Singh

ResourceFunction["MagicSquare"][n]

gives a magic square of dimension n.

Details and Options

A magic square is a 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

Get a 3×3 magic square:

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

Get a 5×5 magic square:

In[2]:=
ResourceFunction["MagicSquare"][5] // Grid
Out[2]=
In[3]:=
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[3]=

Check that row, column, main diagonal and antidiagonal sums all agree:

In[4]:=
Plus @@@ ResourceFunction["MagicSquare"][5]
Out[4]=
In[5]:=
Plus @@@ Transpose[ResourceFunction["MagicSquare"][5]]
Out[5]=
In[6]:=
Tr[ResourceFunction["MagicSquare"][5]]
Out[6]=
In[7]:=
Tr[Reverse[ResourceFunction["MagicSquare"][5]]]
Out[7]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information