IBM ILOG Solver User's Manual > The Basics > Searching with Predefined Goals: Magic Square > Suggested answers > Exercise 4

Change the program to search for a Gnomon magic square, which is a n = 4 magic square in which the elements in each quarter (2 x 2 corner) have the same sum.

Suggested Answer

Describe

Model

Solve

The code that has changed from magicsq.cpp follows. You can view the complete program online in the file YourSolverHome/examples/src/magicsq_ex4.cpp.

The size of the magic square is set to 4:

int main() {
  IloEnv env;
  try {
    IloModel model(env);
    IloInt n = 4;

You should add the following additional constraints:

    // Constraint on upper left quarter
    IloExpr exp3(env);
    for (i = 0; i < 2; i++)
      for(j = 0; j < 2; j++)
        exp3 += square[i+n*j];
        model.add(exp3 == sum);
        exp3.end();
    // Constraint on upper right quarter
    IloExpr exp4(env);
    for (i = 2; i < n; i++)
      for(j = 0; j < 2; j++)
        exp4 += square[i+n*j];
        model.add(exp4 == sum);
        exp4.end();
    // Constraint on lower left quarter
    IloExpr exp5(env);
    for (i = 0; i < 2; i++)
      for(j = 2; j < n; j++)
        exp5 += square[i+n*j];
        model.add(exp5 == sum);
        exp5.end();
    // Constraint on lower right quarter
    IloExpr exp6(env);
    for (i = 2; i < n; i++)
      for(j = 2; j < n; j++)
        exp6 += square[i+n*j];
        model.add(exp6 == sum);
        exp6.end();

You should obtain the following result:

Feasible Solution
 1 4 13 16
 14 15 2 3
 8 5 12 9
 11 10 7 6