Mathematica programming

Friday, July 22, 2005

Magic Squares


Magic square is a square of integer numbers such that sum
of numbers in each row, each column and two diagonals
are the same.


Generating magic squares is easy with Mathematica. For instance,
solving for 4 by 4 matrices

vars = Variables[matrix = Array[a, {4, 4}]];

eqs = Equal @@ Join[
Plus @@@ matrix, (* sum of rows *)
Plus @@@ Transpose[matrix], (* of columns *)
{Tr[matrix ], Tr[Reverse /@ matrix] } (* of diagonals *)
];

sol =
matrix /. ToRules[And @@
Cases[Reduce[eqs , vars, Integers], _Equal]]

we get an answer in terms of free 8 integers

{{n1, n2, n3, n4},
{n5, n6, n7, n1 + n2 + n3 + n4 - n5 - n6 - n7},
{n8, n1 - n4 + n5 - n7 + n8,
n2 + n3 + 2 n4 - n5 - n6 - n8, n6 + n7 - n8},
{n2 + n3 + n4 - n5 - n8, n3 + 2 n4 - n5 - n6 +
n7 - n8, n1 - n3 - n4 + n5 + n6 - n7 + n8,
-n4 + n5 + n8}
}

0 Comments:

Post a Comment

<< Home