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'.
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:
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:
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.
|1.0.0||source & binary||~30KB||MagicQS is a command-line tool implemented in portable ANSI C. Both binaries (for Windows) and complete source code are available for free download.|