Magic Squares Generator

There are a lot of magic squares types, but here, a magic square is a square matrix made of subsequent natural numbers, whose sums for each row, column, and the two main diagonals are equal. Magic squares such as those defined above are called 'perfect squares'.

1

n=1

8

1

6

3

5

7

4

9

2


n=3

17

24

1

8

15

23

5

7

14

16

4

6

13

20

22

10

12

19

21

3

11

18

25

2

9


n=5

30

39

48

1

10

19

28

38

47

7

9

18

27

29

46

6

8

17

26

35

37

5

14

16

25

34

36

45

13

15

24

33

42

44

4

21

23

32

41

43

3

12

22

31

40

49

2

11

20


n=7

The squares shown above are the base perfect squares, where the numbers from 1 to 'N', where 'N' is the number of elements in the matrix (N = n2 e.g., 3x3 = 9), are used only once. Adding the same number to every square element, or multiplying it by the same number, produces other magic squares of the same family.

Generate your own Magic Square

This online demo generates magic suares of odd sizes (1,3,5,7, ...) , in a new window:

Matrix size N (NxN, N must be odd):
(requires Javascript)

MagicSQ

MagicSQ implements a simple algorithm (Simon de la Loubère's) for creating squares of the same type as shown above. It can create base perfect squares of any size and is limited only by the memory in your system and by your time. It is a polynomial time algorithm of O(n2) and has a n2 space complexity. The above tables were generated by this program.

The n-odd magic square algorithm is easy to learn by heart and could be great for impressing kids. For an explanation of the algorithm used in the MagicSQ generator see:
http://forum.swarthmore.edu/alejandre/magic.square/adler/adler.5x5math.html.

Suprisingly a generic algorithm exists for generating also n-even magic squares by Kwon Young Shin. The original program is modified, here, to make use of dynamic memory allocation, in order to allow the creation of squares with a big number of elements. It uses 's_matrix.h' and 's_matrix.c' files. Replace 'magicsq.c' by the 'kwon.c' file when compiling.

I am not a mathematician, do not ask me on this. I was taught the n-odd algorithm on paper when I was very young by my grandfather, before I could learn to program, and found it very fascinating. Later on, when I could program (and my grandfather was no more there), I became aware what he had taught to me was what they call an algorithm. I implemented it in C to test some bigger numbers than I could test on paper when I was a child.

Download


MagicQS

VersionTypeFileSizeComment
1.0.0source & binary
~30KBMagicQS is a command-line tool implemented in portable ANSI C. Both binaries (for Windows) and complete source code are available for free download.