A magic square is an square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the *magic number* or *magic constant*).

The numbers are usually (but not always) the 1^{st} *N*^{2} positive integers.

A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a *semimagic square*.

- Task

For any odd *N*, generate a magic square with the integers [1, *N*^{2}] and show the results. Optionally, show the*magic number*.

You should demonstrate the generator by showing at least a magic square for *N* = 5.

#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr() { sqr = 0; } ~magicSqr() { if( sqr ) delete [] sqr; } void create( int d ) { if( sqr ) delete [] sqr; if( !( d & 1 ) ) d++; sz = d; sqr = new int[sz * sz]; memset( sqr, 0, sz * sz * sizeof( int ) ); fillSqr(); } void display() { cout << "Odd Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) cout << setw( l + 2 ) << sqr[yy + x]; cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { int sx = sz / 2, sy = 0, c = 0; while( c < sz * sz ) { if( !sqr[sx + sy * sz] ) { sqr[sx + sy * sz]= c + 1; inc( sx ); dec( sy ); c++; } else { dec( sx ); inc( sy ); inc( sy ); } } } int magicNumber() { return ( ( ( sz * sz + 1 ) / 2 ) * sz ); } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s; s.create( 5 ); s.display(); return system( "pause" ); }

- Output:

Odd Magic Square: 5 x 5 It's Magic Sum is: 65 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 Odd Magic Square: 7 x 7 It's Magic Sum is: 175 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20

Content is available under GNU Free Documentation License 1.2.