Skip to content

Instantly share code, notes, and snippets.

@AnowarCST
Last active August 29, 2015 14:17
Show Gist options
  • Save AnowarCST/76cdc96c0d72f4c4acc1 to your computer and use it in GitHub Desktop.
Save AnowarCST/76cdc96c0d72f4c4acc1 to your computer and use it in GitHub Desktop.
Magic square
// Magic square Algorithm
/*
* Logic:
1. set 1 in first row centre
2. then upper->left = key [key=2,3,4....]
3. if not empty (upper->left) then find the buttom of last node = key
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i,j,key,x=0,y=0;
int n = 3;//this is must be odd number
int sq[n][n];
if(n%2==0) {
cout<<"N must be odd number";
return 0;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
sq[i][j] = 0;
i= 0;
j= (n-1)/2;
sq[i][j] =1;
for(key=2;key<=n*n;key++){
i--;
j--;
i= (i<0)? n-1:i;
j= (j<0)? n-1:j;
if(sq[i][j]>=1){
i=x+1;
j=y;
}else{
x=i;
y=j;
}
sq[i][j] = key;
}
//for output
for(i=0;i<n;i++){
for(j=0;j<n;j++)
cout<<sq[i][j]<<"|";
cout<<endl;
}
int s=0;
for(i=0;i<n;i++) s=s+sq[0][i];
cout<<"Total: "<<s;
return 0;
}
@AnowarCST
Copy link
Author

try with this: http://cpp.sh/8cac

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment