对每个N,使得1,2,3..N^2,排列成N×N矩阵,并且横、竖、两条对角线的和都相等。

#include <vector>
#include <algorithm>
#include <iostream>
#include <iomanip>
using namespace std;

typedef vector< vector<int> > Matrix;

inline void Print( const Matrix& array, int size )
{
  for (int i=1; i<=size; ++i )
  {
    for (int j=1; j<=size; ++j )
      cout << setw(5) << array[i][j];
    cout << endl;
  }
}

inline void Meshgrid( Matrix& A, Matrix& B, int size )
{
  for (int i=1; i<=size; ++i )
    for (int j=1; j<=size; ++j )
      A[i][j] = j, B[i][j] = i;
}

void Magic( Matrix& mat, int size );

int main()
{
  int N;
  cout << "Input a Number:\n";
  cin >> N;
  if ( N > 1000 )
  {
    cout << "The Number Inputed is Too Large!\n ";
    return 1;
  }
  Matrix Array(N+1);
  for ( int i=1; i<=N; ++i )
  {
    Array[i] = vector<int>(N+1);
  }
  
  Magic( Array, N );
  
  cout << "The Magic Square sizeof (" <<N<<" * "<<N<<") is below:\n\n";
  Print( Array, N );
  cout << endl;
  
  return 0;
}


void Magic(Matrix& array, int n)
{
  int i, j;
  Matrix I, J, A, B;
  I = J = A = B = array;
  
  for (i=1; i<=n; i++ )
    for (j=1; j<=n; j++ )
      A[i][j] = 0, B[i][j] = 0;
  
  if ( n%2 == 1 ) // 奇数
  {
    Meshgrid(J, I, n);
    for (i=1; i<=n; i++ )
      for (j=1; j<=n; j++ )
      {
        A[i][j] = ( I[i][j] + J[i][j] -(n+3)/2 + n ) % n;
        B[i][j] = ( I[i][j] + 2*J[i][j] - 2 + n ) % n;
      }
    for (i=1; i<=n; i++ )
      for (j=1; j<=n; j++ )
        array[i][j] = n*A[i][j] + B[i][j] + 1;
  }
  else if ( n%4 == 0 ) // 4的倍数
  {
    Meshgrid(J, I, n);
    for (i=1; i<=n; i++ )
      for (j=1; j<=n; j++ )
        A[i][j] = ( (I[i][j]%4)/2 == (J[i][j]%4)/2 );
    
    for (int k=1, i=1; i<=n; i++ )
      for (j=1; j<=n; j++ )
      {
        array[i][j] = k++;
        if ( A[i][j] == 1 )
        {
          array[i][j] = n*n + 1 - array[i][j];
        }
      }
  }
  else // 2的倍数且非4的倍数
  {
    int p;
    int k;
    p = n/2;
    Magic(array,p);
    for (i=1; i<=p; i++ )
    {
      for (j=1; j<=p; j++ )
      {
        array[i][j+p] = array[i][j] + 2*p*p;
        array[i+p][j] = array[i][j] + 3*p*p;
        array[i+p][j+p] = array[i][j] + p*p;
      }
    }
    if ( n == 2 )
    {
      return;
    }
    k = (n-2)/4;
    for (i=1; i<=p; i++ )
    {
      for (j=1; j<=k; j++ )
      {
        swap(array[i][j], array[i+p][j]);
      }
    }
    for (i=1; i<=p; i++ )
    {
      for (j=n-k+2; j<=n; j++ )
      {
        swap(array[i][j], array[i+p][j]);
      }
    }
    i = k+1;
    swap( array[i][1], array[i+p][1] );
    swap( array[i][i], array[i+p][i] );
  }
}

比如:

Input a Number:
5
The Magic Square sizeof (5 * 5) is below:

   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

参考资料