Skip to content

Instantly share code, notes, and snippets.

@cohalz
Created September 24, 2013 04:42
Show Gist options
  • Save cohalz/6680467 to your computer and use it in GitHub Desktop.
Save cohalz/6680467 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define maxRow 10 //最大行数
int main(void) {
int i,j,n,sumNum; //nは正方行列の大きさ、sumNumは魔方陣であった場合の各要素の和。
int arr[maxRow][maxRow]; //行列。
int row[maxRow] = {0}; //各行の要素の和が入る。
int column[maxRow] = {0}; //各列の要素の和が入る。
int cross[2] = {0}; //斜め(cross[0]は右下がり,cross[1]は右上がり)の要素の和が入る。
int numFlag[maxRow*maxRow] = {0}; //各数字が出た回数、例えば1が2回出たならnumFlag[0]が2になる。
printf("n = ");
while(scanf("%d", &n) != 1 || n < 3 || n > maxRow) {
printf("#matrix must be at least 3 and at most %d.\n",maxRow);
while(getchar() != '\n') {};
printf("n = ");
}
sumNum = (n*(n*n+1))/2;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf("row%d,column%d = ",i,j);
while(scanf("%d",&arr[i][j]) != 1 || arr[i][j] < 1 || arr[i][j] > n*n) {
while(getchar() != '\n') {};
printf("row%d,column%d = ",i,j);
}
}
}
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf("%3d ",arr[i][j]);
row[i] += arr[i][j];
column[i] += arr[j][i];
numFlag[arr[i][j]-1]++; //arr[i][j]の要素が2ならnumFlag[1]を1増やし、各数字が何回出たか数えていく。
}
puts("");
cross[0] += arr[i][i];
cross[1] += arr[i][n-i-1];
}
for(i=0;i<n;i++) {
if(row[i] != sumNum || column[i] != sumNum) {
puts("It isn't magic square.");
return 0;
}
}
for(i=0;i<n*n;i++) {
if(numFlag[i] != 1) {
puts("It isn't magic square.");
return 0;
}
}
if(cross[0] != sumNum || cross[1] != sumNum) {
puts("It isn't magic square.");
return 0;
}
puts("It is magic square!");
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment