This Java Script calculator generates magic squares for of a given size. To operate, enter the desired size (to get a 4 x 4 magic square enter 4). Then, press the Compute button to generate a magic square in a separate window. On invalid entries, a popup window will display an error message.
Return to Contents
The Java Script source code for this program can be viewed by using the View|Source command of your web browser.
You may use or modify this source code in any way you find useful, provided that you agree that the author has no warranty, obligations or liability. You must determine the suitability of this source code for your use.
Return to Contents
Definition and properties
A magic square is an arrangement of the numbers from 1...N2 in an N x N matrix, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or either main diagonal is equal to the magic constant defined as:
M2 = N·(N2 + 1)/2
The simplest magic square is the 1 x 1 magic square whose only entry is the number 1. There is no 2 x 2 magic square. The next simplest is the 3 x 3 magic square:
8 1 6 3 5 7 4 9 2
Production
A technique known as the Siamese method can be used to generate magic squares with odd sizes (3, 5, 7, 9,...). It begins by placing a 1 in any location. Then, sequentially, numbers are added in squares one unit above and to the right. The process wraps around as if the square pattern repeats on all sides. When a square is encountered, which is already filled, the next number is placed below the previous one and the process continues until all squares are filled.
Another method known as the big X method constructs magic squares of doubly even order sizes (4, 8, 12, 16,...). In this method, all squares are filled in sequence. The X's are the diagonals of each 4 x 4 block of squares. The order of the entries, in these diagonals, is reversed. In an 8 x 8 magic square, the diagonal numbers are 1, 4, 5, 8,..., 60, 61, and 64; so entry 1 is replaced with 64, 4 with 61, 5 with 60, and so on.
A method known as the LUX method constructs magic squares of singly even order sizes (6, 10, 14, 18,...). For a size N, compute m = (N - 2)/4. Then create a (2·m + 1) x (2·m + 1) array with m + 1 rows of Ls, 1 row of Us, and m - 1 rows of Xs. Interchange the middle U with the L above it. Now generate the magic square of order 2·m + 1 using the Siamese method applied to the array of letters (starting in the center letter of the top row), but fill each set of four squares corresponding to a lettered block by the next group of sequential digits using the pattern identified by the letter. The L, U, X patterns are:
L: 4 1 2 3 U: 1 4 2 3 X: 1 4 3 2
References
Return to Contents
AbCd Classics - free on-line books