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 be3$ \le$N$ \le$15. 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;//若该数不再表格边缘,跳到下一行
			}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值