Skip to content

Magic Squares

Vector 17:1, page 40

mathematics and statistics competitions and puzzles user interfaces

Transcribed from the printed issue; not yet reviewed. Read it in the PDF of the issue, page 40

In the geocentric cosmology of Ptolemy, the classical seven planets (which include the sun and moon, but don’t include any beyond Saturn because they hadn’t been discovered) each sit more or less tightly on their own steadily rotating crystal sphere surrounding the earth. The fixed stars are attached to an outermost sphere. Amazingly all the spheres share roughly the same rotational axis, which causes the planets to confine themselves to a narrow band of fixed stars called the zodiac (a Chaldean word). The further away the planets are, the slower they creep round the zodiac, with dull old Saturn being the slowest of all. In fact they can be ranked from the slowest to the fastest like this:

SERIES←'SATURN' 'JUPITER' 'MARS' 'SUN' 'VENUS' 'MERCURY' 'MOON'

a fact known from antiquity. Modernists who can’t think back past the heliocentric theory might care to note that if ‘EARTH’ is substituted for ‘SUN’, and omitting ‘MOON’ (which even the heliocentric theory recognises as going round the earth) then this ancient SERIES describes the planets in reverse order of mean distance (d) from the sun. Furthermore, d increases with orbital period (t) according to the formula d3=kt2. This is the Third Law of Johannes Kepler (1571–1630), who predated Isaac Newton (1642-1727) by over a century.

Do you know how the days of the week got their names? In ancient times the Chaldeans actually assigned them to planets in the following sequence, based on their order in SERIES:

      (7 3⍴SERIES)[;1]
SATURN  SUN  MOON  MARS  MERCURY  JUPITER  VENUS

The Chaldeans, not possessing computers, or at least computers running APL, employed the ancient sacred geometric figure known as the heptagram to compute the above expression. The original planetary god-names are most clearly seen in French, Spanish and Italian names for the days of the week, but if you map the Roman gods onto corresponding Germanic gods, you can see it in English too. Thus: Mars = Tiw (war god), giving Tuesday; Mercury = Woden (smart god), giving Wednesday; Jove = Thor (thunder god), giving Thursday; Venus = Freya (love goddess), giving Friday; and Saturn, Sun and Moon of course giving Saturday, Sunday and Monday respectively.

Not only did the planets get their very own days of the week in antiquity, but they also got their very own magic squares. Seven magic squares of orders 3 thru 9 were assigned to the planets in terms of the rate they orbited round the zodiac (i.e. in the sequence of SERIES), thus Saturn got the smallest order (3) and Moon got the largest (9). Here they are:

SATURN  JUPITER      MARS            SUN
4 9 2    4 14 15  1  11 24  7 20  3   6 32  3 34 35  1
3 5 7    9  7  6 12   4 12 25  8 16   7 11 27 28  8 30
8 1 6    5 11 10  8  17  5 13 21  9  19 14 16 15 23 24
        16  2  3 13  10 18  1 14 22  18 20 22 21 17 13
                     23  6 19  2 15  25 29 10  9 26 12
                                     36  5 33  4  2 31

VENUS                 MERCURY                  MOON
22 47 16 41 10 35  4   8 58 59  5  4 62 63  1  37 78 29 70 21 62 13 54  5
 5 23 48 17 42 11 29  49 15 14 52 53 11 10 56   6 38 79 30 71 22 63 14 46
30  6 24 49 18 36 12  41 23 22 44 45 19 18 48  47  7 39 80 31 72 23 55 15
13 31  7 25 43 19 37  32 34 35 29 28 38 39 25  16 48  8 40 81 32 64 24 56
38 14 32  1 26 44 20  40 26 27 37 36 30 31 33  57 17 49  9 41 73 33 65 25
21 39  8 33  2 27 45  17 47 46 20 21 43 42 24  26 58 18 50  1 42 74 34 66
46 15 40  9 34  3 28   9 55 54 12 13 51 50 16  67 27 59 10 51  2 43 75 35
                      64  2  3 61 60  6  7 57  36 68 19 60 11 52  3 44 76
                                               77 28 69 20 61 12 53  4 45

A magic square of order \(n\) is an arrangement of the first \(n^2\) natural numbers in an \(n\)-by-\(n\) square, such that each of the \(n\) rows, \(n\) columns, and 2 main diagonals, sums to the same total: \(m\). If you look at the function listing in the appendix, you see that the function: magic (which returns 1 if a given matrix is a magic square, 0 otherwise) computes these totals in order to check they are all the same.

Without knowing anything else about the magic square, what must the number \(m\) be? Well, since there are \(n\) rows, each totalling \(m\), and furthermore the grand total of the whole square is the sum of the first \(N\) natural numbers (\(\tfrac{1}{2}N(1+N)\)), where \(N= n^2\), it follows that (in ordinary arithmetic notation):

\[\begin{equation*} mn = \tfrac{1}{2}\, n^2\, (1+n^2) \end{equation*}\]

or, dividing through by \(n\):

\[\begin{equation*} m = \tfrac{1}{2}n(1+n^2) = \tfrac{1}{2}(n+n^3) \end{equation*}\]

which in Dyalog version 8.2 can be defined as an in-line function like this:

      total←{0.5×⍵+⍵*3}

The main use of magic squares from the Chaldeans onwards was in the drawing of talismans. Thus to inscribe the matrix SUN say, was to enshrine in the talisman the special virtues of the sun, namely: strength, majesty, imperium, etc. But in place of the whole magic square, you could use just the grand total, called its magic number. These numbers have an important significance in the occult art known as gematria. For example, summing along each row of SUN we get:

      +/SUN
111 111 111 111 111 111

and summing the row sums themselves we get the grand total, or magic number:

      +/+/SUN
666

…the number of the Beast! Would you have guessed it had anything to do with the sun?

It seems these seven magic squares were passed on down through the ages in exactly the same layout, so that occultists talk of the magic square of order 7, or the magic square of Venus. But are these the only magic squares of a given order? Of course not. Clearly you can transpose a magic square and this preserves the magic property, since rows become columns and vice-versa, but more importantly the two diagonals are mapped onto themselves. Thus:

      magic ⍉VENUS
1

You can also find permutations of rows and columns which preserve the magic property. Applying the same permutation to rows and columns will map the first diagonal onto itself, but if the permutation is its own mirror image this preserve the second diagonal also. One such permutation is (⌽⍳7): In fact all rotations, transpositions and reflections will work, because the contents of any row, column or diagonal keep together, so they will always sum to the value they did before.

      (⌽⍳7)rc VENUS
28  3 34  9 40 15 46
45 27  2 33  8 39 21
20 44 26  1 32 14 38
37 19 43 25  7 31 13
12 36 18 49 24  6 30
29 11 42 17 48 23  5
 4 35 10 41 16 47 22
      magic (⌽⍳7)rc VENUS
1

Notice too that you can make an essentially new magic square by replacing the highest number (49) with 1, the next highest with 2, and so on. In fact this is equivalent to calculating (50-VENUS), and so we can verify:

      magic 50-VENUS
1

Does this work with any magic square (using \(1+n^2\) in place of 50)? Yes. We’ll prove it by using APL notation itself. (How often do you see APL used for mathematical proofs? Why not? It’s a formal language, isn’t it?)

Let \(n\) be the order of the magic square (\(n=7\) for VENUS) and let a be any vector of \(n\) elements summing to the row-total (call it: N) So:

      N=+/a

Now replacing every element a[i] of a with (1+n*2)-a[i], and summing it all, is equivalent to the expression:

      +/(1+n*2)-a

The subexpression in brackets, (1+n*2), is scalar, but combining it with a makes it behave like a vector of n equal elements. So, by simple arithmetic operations, the following equivalent lines can be successively derived:

      +/(1+n*2)-a
      (+/n⍴(1+n*2))-(+/a)
      (n×(1+n*2))  -(+/a)
      (n+n*3)      -(+/a)
      (2×N)        -N
      N

You’ll recognise the bracketed subexpression (n+n*3) in the last line but-one as equalling 2×N from the definition of fn: total. Since this applies to any vector of \(n\) integers summing to N, it applies to every row, column and diagonal of any given magic square of order n.

But let us ask: how many distinct magic squares are there of order \(n\), if we don’t distinguish row/column permutations, rotations or reflections of a given square? For \(n=3\) there is only one, namely SATURN. To see this, run the fn: comb with arg 3 (the order of the magic square). A listing of: comb is appended to this article. Fn: comb returns a set of Boolean vectors, each designating a choice of 3 numbers from ⍳3*2 which happens to sum to (total 3). All such vectors are found. If you want to see the numbers this corresponds to, run fn: ros on the result of comb.

      ↑comb 3
1 0 0 0 1 0 0 0 1
1 0 0 0 0 1 0 1 0
0 1 0 1 0 0 0 0 1
0 1 0 0 1 0 0 1 0
0 1 0 0 0 1 1 0 0
0 0 1 1 0 0 0 1 0
0 0 1 0 1 0 1 0 0
0 0 0 1 1 1 0 0 0
      ros comb 3
 1 5 9  1 6 8  2 4 9  2 5 8  2 6 7  3 4 8  3 5 7  4 5 6

You see that there are only 8 possible distinct magic triples (let’s call them) – combinations of numbers which add to (total 3) = 9. Yet SATURN contains 8 distinct magic triples, 3 rows, 3 columns and 2 diagonals. So SATURN contains every possible magic triple.

In my university course on Computing I occasionally used this fact to cause a student with no intellectual pretensions to win a best-of-three contest against one of the self-acknowledged brightest students in the class (to the latter’s exquisite chagrin!). I had them ‘volunteer’ to challenge each other to ‘Number Scrabble’, a game played with 9 counters numbered 1 to 9 placed face-up between two players. Each player take one counter in turn. The aim is to be the first to exhibit a selection of three counters summing to 15. Deceptively simple. Here’s a sample game to illustrate some of its subtlety:

  1. Player 1 takes 5 — holds: 5
  2. Player 2 takes 2 — holds: 2
  3. Player 1 takes 8 — holds: 5 8
  4. Player 2 takes 9 — holds: 2 9
  5. Player 1 takes 4 — holds: 5 8 4, stopping Player 2 from taking 4 to win with 2+9+4
  6. Player 2 takes 3 — holds: 2 9 3, stopping Player 1 from taking 3 to win with 8+4+3
  7. Player 1 takes 6 — holds: 5 8 4 6, winning anyway with 4+5+6.

Number Scrabble places an enormous cognitive load on the player, who must be continually making trial additions of various combinations of counters: his own, his opponent’s, plus what-if selections from the pool. However, as Newell and Simon show in Human Problem Solving, the game is mathematically isomorphic to Tic-Tac-Toe – as you’ll see if you arrange the nine counters into the magic square SATURN. Accordingly I surreptitiously equipped my ‘weaker’ student with a Tic-Tac-Toe board marked with the numbers of SATURN, plus instructions to play Tic-Tac-Toe as player ‘O’, simply calling out the number of the square he placed an ‘O’ in, and mark his opponent’s chosen numbers on the board with an ‘X’. Player ‘O’ gets to start first, and should always choose 5.

Here’s the state-of-play in the above game after step 5:

4/O  9/X  2/X
3    5/O  7
8/O  1    6

from which you can see straightaway that ‘X’ cannot win, because ‘O’ can select either 3 or 6 to win. Even to spot this fact is a difficult task in Number Scrabble. But not in Tic-Tac-Toe.

What was the purpose of this class demonstration? That talismans really work? Yes, but not in the superstitious sense. The design of any interactive computer system should display its information in a choice of cognitive domain that the user is most proficient in. In the present case, one which demands simple spatial awareness is demonstrably better than one which demands mental arithmetic on simultaneous expressions. You might go so far as to say that, whatever the application, if the programmer can discover a ‘magic square’ for it, he or she may have the key to enhancing the end-user’s productivity quite significantly.

It’s obvious when you put it like that. However many programmers think it’s best to present the information to be manipulated in a ‘traditional’ form, i.e. one which might have been used by the operatives before the task was computerised. Taken to its extreme, such programmers would force switching logic designers to work with a display of Aristotelian syllogisms (a mediaeval form of symbolic logic). Perversely, that might be just the interface to use if you had to recruit your logic designers from a pool of classics graduates!

Returning to magic squares, might it be that JUPITER (order 4) holds the key to playing an extended Number Scrabble with 16 counters, from which four must be selected to add to 34 (34=total 4)? Alas, no.

Let us run fn: comb once more to find all sets of 4 distinct integers taken from 1..16 and adding to 34:

      ⍴comb 4
86

Now JUPITER exhibits only 10 of these 86 ‘magic quadruples’ (4 rows, 4 columns, 2 diagonals). Which makes me suspect that there are several quite distinct magic squares of order 4, which cannot be transformed into each other by permuting rows, columns, or transposing the matrix.

Is it feasible to generate magic squares systematically? Yes, it’s not at all difficult to generate a magic square of any choice of odd order. The fn: gen1 (listed below) does so, but only works for odd arguments. The magic squares it generates are equivalent to the classical ones under row/column permutation. Thus, using the fn: rc (also listed) to permute the output of gen1 we can show that all these APL expressions yield the value 1 (true):

      SATURN≡gen1 3
      MARS≡4 1 3 5 2 rc gen1 5
      VENUS≡2 5 1 4 7 3 6 rc gen1 7
      MOON≡7 2 6 1 5 9 4 8 3 rc gen1 9

The fns listed below form the beginnings of a toolkit to search for magic squares of any order. The new Dyalog feature dynamic function definition is used for the first 5 functions (but these can be readily rewritten as conventional ‘del’ functions):

      isnatural←{(⍳⍴,⍵)≡(,⍵)[⍋,⍵]}
      eq←{(,1)≡⍴∪,⍵}
      total←{0.5×⍵+⍵*3}
      dia←{((¯1+⍳⊃⍴⍵)⊖⍵)[1;]}
      aid←{((-⍳⊃⍴⍵)⊖⍵)[1;]}

    ∇ Bool←magic z
[1]   ⍝=1 iff z is a magic sq
[2]    Bool←(isnatural z)∧eq(total⊃⍴z),(+/z),(+⌿z),(+/dia z),(+/aid z)
    ∇

    ∇ poll sec
[1]   ⍝look at ⍴z at: sec intervals
[2]    :Repeat
[3]        '>>> ⍴z='(⍴z)
[4]        ⎕DL sec
[5]    :Until 0
    ∇

    ∇ z←comb order;act;sh
[1]   ⍝ways of combining: (order) nos from: ⍳order*2 to add to: (total order)
[2]    act←act1 ⍝--for different actions on all combinations
[3]    sh←{} ⍝--no trace
[4]   ⍝sh←+ ⍝--to trace the combinations tried
[5]    z←⍬ ⍝--used as an accumulator by: act
[6]    poll&1
[7]    ⍬(order comb_sel act)⍳order*2
[8]    ⎕TKILL ⎕TNUMS ⍝--terminate: poll
    ∇

    ∇ jk(order comb_sel act)in;i;j;ijk;me
[1]    ⍝apply act to all combinations or order nos in: in
[2]    me←⍎⍕'order'(⊃⎕SI)'act' ⍝--forms a recursive fn from this op
[3]   ⍝...so you can safely change the op name and it will still recurse!
[4]    j←⊃jk
[5]    :For i :In j↓in ⍝--only bother with i>j in jk
[6]        sh ijk←i,jk ⍝--form new left arg
[7]        :If order>⍴ijk ⍝--then recurse...
[8]            ijk me in
[9]        :Else ⍝--deepest recursion: call the working fn...
[10]           order act1 ijk in
[11]       :EndIf
[12]   :EndFor
    ∇

    ∇ order act1 xy;x;y
[1]   ⍝perform the chosen action inside: comb
[2]    x y←xy ⍝--x: vec of (order) combinations chosen from vec: y
[3]    :If (total order)=+/x
[4]        sh'>>>'x(y∊x)
[5]        z,←⊂y∊x
[6]    :EndIf
    ∇

    ∇ z←ros set;n
[1]   ⍝return nos corresp to bitstrings set
[2]    n←⍴⊃set
[3]    z←set/¨⊂⍳n
    ∇

    ∇ z←gen1 n;y;i;j
[1]   ⍝generate magic sq: 1st strategy
[2]    j←⌈n÷2 ⍝--mid-pt no
[3]    z←n n⍴⍳n ⍝--shaped array
[4]    z←(j-⍳n)⌽z ⍝--upper latin sq with iss property
[5]    y←⌽z ⍝--reverse it to get lower latin sq
[6]    z←y+n×z-1 ⍝--combine z and y
    ∇

    ∇ z←p rc m
[1]   ⍝apply perm: p to rows/cols of m
[2]    z←m[p;p]
    ∇