职业IT人-IT人生活圈

 找回密码
 成为会员
搜索
查看: 953|回复: 1

要求输出1至n^2的自然数构成的幻方阵

[复制链接]
周星星 发表于 2009-8-25 09:43 | 显示全部楼层 |阅读模式
幻方阵是指这样的方阵
它的每一行
每一列和对角线之和均相等
白兔仔 发表于 2009-8-25 09:43 | 显示全部楼层

要求输出1至n^2的自然数构成的幻方阵

只有奇数阶的

#include <iostream.h>
#include <iomanip.h>

#define SIZE 20

void Magic(int n) {
//Create a magic square of size n,n being odd.
int square[SIZE][SIZE];
if(!(n%2)) {cout<<"n is even"<<endl;return;}
else {
for(int i=0;i<n;i++)
//Initialize square to zero.
for(int j=0;j<n;j++) square[j]=0;
square[0][(n-1)/2]=1;
//Middle of first row
//(i,j) is the current position.
int j=(n-1)/2,k,l;
for(int key=2;key<=n*n;key++) {
//Move up and left.The next two if statements
//may be replaced by the % operator if -1%n is
//implemented to have value n-1.
k=(i)?(i-1)n-1);
l=(j)?(j-1)n-1);
if(square[k][l]) i=(i+1)%n;
else {
//square[k][l] is empty.
i=k;j=l;
}
square[j]=key;
}
//Output the magic square.
for(i=0;i<n;i++) {
for(j=0;j<n;j++) cout<<setw(5)<<square[j];
cout<<endl;
}
}
}

void main() {
int n;
cin>>n;
Magic(n);
}
您需要登录后才可以回帖 登录 | 成为会员

本版积分规则

QQ|手机版|小黑屋|网站帮助|职业IT人-IT人生活圈 ( 粤ICP备12053935号-1 )|网站地图
本站文章版权归原发布者及原出处所有。内容为作者个人观点,并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是信息平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽造成漏登,请及时联系我们,我们将根据著作权人的要求立即更正或者删除有关内容。

GMT+8, 2024-3-29 16:36 , Processed in 0.141913 second(s), 20 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表