magic square

 

Magic Square

Time Limit: 3000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu

[Submit] [Go Back] [Status]

Description

If you have good observations skills, you may found that building a Magic Square is simple. A Magic Square has only an odd numberN of rows and columns. For this problem you could expect the values to be3N15. A Magic Square is created by integer numbers in the range from 1 to N2, with a peculiar property, the ``sum of the numbers" in each row, column and diagonal is the same value.


For example the case for n = 3 is:

M. Square                Rows          Columns       Diagonals
 8 1 6                   8+1+6 = 15    8+3+4 = 15    8+5+2 = 15
 3 5 7                   3+5+7 = 15    1+5+9 = 15    4+5+6 = 15
 4 9 2                   4+9+2 = 15    6+7+2 = 15


Hint: Imagine that the square is rounded. That is, the last row is connected with the first row and the last column is connected with the first column. As shown in the examples, the starting point is the center of the first row and observe how the numbers are placed following diagonals. There is only one more thing to observe, what happens when you find a cell that is already in use.

Input

A file with several lines, each line has the value of n.

Output

For each input line, print N and the sum in the first line, followed by the magic square. To see a nice looking square, take into account the maximum length in characters ofN2 and print each number with the maximum length preceded by one space or blank character. Print one line between squares.

Sample Input

3
5

Sample Output

n=3, sum=15
 8 1 6
 3 5 7
 4 9 2

n=5, sum=65
 17 24  1  8 15
 23  5  7 14 16
  4  6 13 20 22
 10 12 19 21  3
 11 18 25  2  9

数组从1开始

1的位置,当N为奇数时候,在正中间,N为偶数的时候,在中间左边,所以1的位置就是(N+1)/2;

2的位置,在1的下一列最后一行

3的位置,若右上角有数或到边缘了,则在2的上一行最左边的一列

4的位置,若右上角有数或到边缘,则在3的下一行同一列的位置,否则在斜边缘

同理。。。。

	memset(board,0,sizeof(board));
        h=1;
		l=(N+1)/2;//算1的位置
        for(k=1;k<=N*N;k++)
		{
			if(board[h][l]==0)
			{
				board[h][l]=k;
				h=(h-1)%N; if(h==0) h=N;
				l=(l+1)%N; if(l==0) l=N;
				if(board[h][l]!=0) 
				{
					h=(h+2)%N; if(h==0) h=N;
					l=(l-1)%N; if(l==0) l=N; 
				}
			}
			else
			{
				board[(h=h+1)][l]=k;//若该数不再表格边缘,跳到下一行
			}


 

你可能感兴趣的:(File,Integer,input,each,64bit,Numbers)