Generate magic square terms

352 Views Asked by At

I was looking at the Wikipedia page on magic squares, which gave the following equation to generate the numbers for a given square:

$$n \left( \left( i + j - 1 + \frac{n}{2} \right) \mod n \right) + \left( \left(i + 2j - 2 \right) \mod n \right) + 1$$

where $i$ and $j$ are rows and columns. However, it doesn't seem to generate the correct numbers.

For example, for a $3 \times 3$ magic square, the first element should be $8$, but if I plug in $i=1$, $j=1$, $n=3$ into the equation, I get $9.5$. What's the deal?

2

There are 2 best solutions below

1
On BEST ANSWER

There should be $\lfloor\frac{n}{2}\rfloor=\lfloor\frac{3}{2}\rfloor=1$, not $\frac{n}{2}$

http://en.wikipedia.org/wiki/Floor_and_ceiling_functions

0
On

Also, Matlab has the function magic(N) which will generate a magic square of any size N greater than 0 but not equal to 2.

From Matlab help:

MAGIC Magic square. MAGIC(N) is an N-by-N matrix constructed from the integers 1 through N^2 with equal row, column, and diagonal sums. Produces valid magic squares for all N > 0 except N = 2.