Search code examples
phpmagic-square

Construct a Magic Square by a given number of rows


I'm trying to build an application in simple PHP but could be done in any language.

I want the user to enter number of rows and the output will be the magic square of it.

For example, for $rows=3:

8-1-6
3-5-7
4-9-2

Notice that in every row,column,diagonal the sum of numbers is equal to 15.

There is a method for constructing this with an odd number of rows. I DONT want that. I want the program to ACTUALLY calculate numbers, row-sums, column-sums and diagonal-sums, doesn't matter if the input is odd or even.

Do you have any idea how to go about doing this? Right now i'm drowning in a sea of loops. HELP!


Solution

  • Sorry, after a further search I found a JAVA applet that does it: link text

    It's pretty sweet thinking about the extensive mechanism working behind this seemingly simple algorithm.