At First You have to understand Magic square algorithm: Here is Magic Square Algorithm
I got Presentation Error More Than 5 Times due to spacing. Spacing Hints: 1 digit 1Space, 2 digit 2 Space, 3 Digit 3 Space. Here is my Accepted Code After Formatting Space:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,sum,s,a[100][100],i,j,k=0,c,m,l,b=0;
while(cin>>n)
{
m=n*n;
memset(a,0,sizeof(a));
sum=(m*(m+1))/2;
s=sum/n;
i=n/2;
j=n-1;
a[i][j]=1;
for(c=2;c<=m;c++)
{
i=i-1;
j=j+1;
if(i==-1 && j!=n)
{
i=n-1;
}
else if(i>=0 && j==n)
{
j=0;
}
else if(i==-1 && j==n)
{
i=0;
j=n-2;
}
else if(a[i][j])
{
i=i+1;
j=j-2;
}
a[i][j]=c;
//cout<<a[i][j]<<"="<<i<<" "<<j<<endl;
}
if(k>0)
{
printf("\n");
}
k++;
printf("n=%d, sum=%d\n",n,s);
if(n==3)
{
for(j=n-1;j>=0;j--)
{
for(i=n-1;i>=0;i--)
{
printf(" ");
printf("%1d",a[i][j]);
}
printf("\n");
}
}
else if(n>=5 && n<=9)
{
for(j=n-1;j>=0;j--)
{
for(i=n-1;i>=0;i--)
{
printf(" ");
printf("%2d",a[i][j]);
}
printf("\n");
}
}
else if(n>9)
{
for(j=n-1;j>=0;j--)
{
for(i=n-1;i>=0;i--)
{
printf(" ");
printf("%3d",a[i][j]);
}
printf("\n");
}
}
}
return 0;
}
0 comments:
Post a Comment