hi,

there probably is some. There are a lot of different algorithms... as I recall

the simplest works on odd-edged squares and doesn't require any swapping

after the initial generation of the square. Note that adding a constant to

every square or multiplying every square by a constant ends you up with a still

valid magic square, so basically we can talk about squares that start from 1 and

end with the number that is the square of one of the edges.

So you pick a place on an edge (not a corner) and put the number one there.

Then you make a knight's move (ala chess) in any direction, and continue on that

way until you hit a square that has something in it. Note you HAVE to make the

knight's move in the same direction every time. When you hit a square that has

something in it, go back to the last square you put something in and move one

square in the direction of the long edge of the knight's move. Put your next

number there, then start making knight's moves again. Do those two steps

continuously until you have filled the square.

this works for ODD-EDGED squares only. Even edged squares are a real

hassle and I don't remember much about them... as well there are other

algorithms for odd-edged squares but I think this is the simplest.

There is a book about this, if it is still in print. Don't remember the title

(I think it was something along the lines of 'magic squares and cubes'), but, it

was printed by DOVER publishing.

For example:

x 1 x

3 x x

x x 2

then a knight's move won't work so you do:

x 1 x

3 x x

4 x 2

and continue

x 1 6

3 5 x

4 x 2

and then a knight's move won't work so you do

x 1 6

3 5 7

4 x 2

and finish:

8 1 6

3 5 7

4 9 2

which is a valid magic square. Like I say that algorithm should work for

any odd-edged square...

David

Quote:

> Anyone know where I can find example code to find magic squares?

--

---------------------------------------------------------------

http://www.ladsoft.com (computer page)

http://www.geocities.com/Area51/Station/5196/index.html (home page)

http://www.geocities.com/Area51/Station/5196/ttc.html (tao te ching)