奇數(shù)階魔方陣是指由1到n2(n為奇數(shù))個(gè)自然數(shù)構(gòu)成的n*n的方陣,它的每一行,每一列,和對(duì)角線各元素之和均相等,3階的魔方陣如下:
8 1 6
3 5 7
4 9 2
n階魔方陣的構(gòu)造方法為:
1> 首先把1放在頂行的正中間,然后把后繼數(shù)按順序放置在右上斜的對(duì)角線上;
2> 當(dāng)?shù)竭_(dá)頂行時(shí),下一個(gè)數(shù)放到底行,好像它在頂行的上面;
3> 當(dāng)?shù)竭_(dá)最右列時(shí),下一個(gè)數(shù)放在最左端列,好像它僅靠在右端列的右方;
4> 當(dāng)?shù)竭_(dá)的位置已經(jīng)填好數(shù)時(shí),考試大提示:或到達(dá)右上角的位置時(shí),下一個(gè)數(shù)就放在剛填寫的位置的正下方。
C++函數(shù)如下:
/*奇數(shù)階魔方陣問(wèn)題*/
#include
using namespace std;
const int MAX=50;
void main()
{
int matrix[MAX][MAX];
int count;
int row;
int column;
int order;
cout<<"請(qǐng)輸入階數(shù):";
cin>>order;
if(order%2==0)
{
cout<<"階數(shù)必須是一個(gè)奇數(shù),請(qǐng)重新輸入!"< } else
{
row=0;
column=order/2;
for(count=1;count<=order*order;count++)
{
matrix[row][column] = count;
if (count % order == 0)
{
row++;
}
else
{
row = (row == 0) ? order - 1 : row - 1;
column = (column == order-1) ? 0 : column + 1;
}
}
for (row = 0; row < order; row++)
{
for (column = 0; column < order; column++)
{
cout<<"\t"< }
cout< }
}
}
程序運(yùn)行打印出相應(yīng)的n階魔方陣.
8 1 6
3 5 7
4 9 2
n階魔方陣的構(gòu)造方法為:
1> 首先把1放在頂行的正中間,然后把后繼數(shù)按順序放置在右上斜的對(duì)角線上;
2> 當(dāng)?shù)竭_(dá)頂行時(shí),下一個(gè)數(shù)放到底行,好像它在頂行的上面;
3> 當(dāng)?shù)竭_(dá)最右列時(shí),下一個(gè)數(shù)放在最左端列,好像它僅靠在右端列的右方;
4> 當(dāng)?shù)竭_(dá)的位置已經(jīng)填好數(shù)時(shí),考試大提示:或到達(dá)右上角的位置時(shí),下一個(gè)數(shù)就放在剛填寫的位置的正下方。
C++函數(shù)如下:
/*奇數(shù)階魔方陣問(wèn)題*/
#include
using namespace std;
const int MAX=50;
void main()
{
int matrix[MAX][MAX];
int count;
int row;
int column;
int order;
cout<<"請(qǐng)輸入階數(shù):";
cin>>order;
if(order%2==0)
{
cout<<"階數(shù)必須是一個(gè)奇數(shù),請(qǐng)重新輸入!"<
{
row=0;
column=order/2;
for(count=1;count<=order*order;count++)
{
matrix[row][column] = count;
if (count % order == 0)
{
row++;
}
else
{
row = (row == 0) ? order - 1 : row - 1;
column = (column == order-1) ? 0 : column + 1;
}
}
for (row = 0; row < order; row++)
{
for (column = 0; column < order; column++)
{
cout<<"\t"<
cout<
}
}
程序運(yùn)行打印出相應(yīng)的n階魔方陣.