# Help with Magic square program

• 02-16-2011, 03:31 AM
kkGG
Help with Magic square program
I'm writing a program that will take in a user-inputed sequence and determine if what they entered is a magic square. So I need to test: 1) did the user enter n^2 numbers, 2) there are no repeated numbers, and 3) row, column, and diagonal sums are all the same. I am having trouble coming up with a way to do 1 and 3.

I am completely stumped on 1) but here is what I have for 3):

Code:

```int nrows, ncolumns, k = 0, rsum = 0, csum = 0;                                 nrows = (int)Math.ceil(Math.sqrt((double) square.size()));                 ncolumns = nrows;                                 for (int r = 0; r < nrows; r++) {                         while (k < ncolumns) {                                 rsum += square.get(k);                                 k++;                         }                 }                 if (rsum%nrows != 0)                         return false;                                 k = 0; }```
I check row sums first, taking the complete sum of all the rows and if that is not divisible by the number of rows, it means that not all the sums were the same so it returns false (not a magic square). I attempted to do the same sort of procedure with the columns but I can't control the indices the same because they jump by row (don't increase by one each time). How should I deal with that? And how should I go about checking the diagonals?

Thanks. Any help appreciated.
• 02-16-2011, 04:14 AM
Junky
Quote:

Originally Posted by kkGG
I check row sums first, taking the complete sum of all the rows and if that is not divisible by the number of rows, it means that not all the sums were the same so it returns false (not a magic square).

1 2 3
4 5 6
7 8 9

1+2+3 = 6
4+5+6 = 15
7+8+9 = 24

6+15+24 = 45

45 / 3 = 15

According to your logic this is a magic square.
• 02-16-2011, 05:10 PM
kkGG
Quote:

Originally Posted by Junky
1 2 3
4 5 6
7 8 9

1+2+3 = 6
4+5+6 = 15
7+8+9 = 24

6+15+24 = 45

45 / 3 = 15

According to your logic this is a magic square.

Well, I'm not done with the program. I know I still need to sheck the columns and diaganols...that is what I am asking for help with...any idea for how to go about doing that?