The MAGIC function is part of the IMLMLIB library. The MAGIC function returns an nn magic square for n. The matrix is a magic square if it contains the integers 1, 2, …, n. If is the trace of , then satisfies the following conditions:
The sum of every row is .
The sum of every column is .
The sum of the antidiagonal is .
There are many algorithms for creating magic squares. The algorithm implemented in the MAGIC function is based on Moler (2011).
The MAGIC function is mainly used to generate examples for documentation, discussion forums, books, and so forth. The following example displays two magic squares:
m3 = Magic(3); m4 = Magic(4); print m3, m4;
Figure 24.202: Magic Squares of Size 3 and 4
m3 | ||
---|---|---|
8 | 1 | 6 |
3 | 5 | 7 |
4 | 9 | 2 |
m4 | |||
---|---|---|---|
16 | 2 | 3 | 13 |
5 | 11 | 10 | 8 |
9 | 7 | 6 | 12 |
4 | 14 | 15 | 1 |