# Combinatorial question

Greetings.

I read that there are 72 magic squares of size 3 and all of them have sum=15.
But when I code it, I only get 8 solutions.

My code is simple:

``````magic_square(S) :-
S = [A, B, C, D, E, F, G, H, I ],
permutation([1, 2, 3, 4, 5, 6, 7, 8, 9], S),
sum_list([A, B, C], Sum),
sum_list([D, E, F], Sum),
sum_list([G, H, I], Sum),
sum_list([A, D, G], Sum),
sum_list([B, E, H], Sum),
sum_list([C, F, I], Sum),
sum_list([A, E, I], Sum),
sum_list([C, E, G], Sum).
``````

Am I doing something wrong?

Dropping two diagonal constraints, your edited codes returns 72.
I am not sure on what is magic squares, but your codes counts
correctly something on magic squares depending on the definition.

``````magic_square(S) :-
S = [A, B, C, D, E, F, G, H, I ],
permutation([1, 2, 3, 4, 5, 6, 7, 8, 9], S),
sum_list([A, B, C], Sum),
sum_list([D, E, F], Sum),
sum_list([G, H, I], Sum),
sum_list([A, D, G], Sum),
sum_list([B, E, H], Sum),
sum_list([C, F, I], Sum).
% sum_list([A, E, I], Sum),
% sum_list([C, E, G], Sum).

% ?- findall(S, magic_square(S),  All), length(All, N).
%@ All = [[1, 5, 9, 6, 7, 2, 8, 3|...], [1, 5, 9, 8, 3, 4, 6|...], [1, 6, 8, 5, 7, 3|...], [1, 6, 8, 9, 2|...], [1, 8, 6, 5|...], [1, 8, 6|...], [1, 9|...], [1|...], [...|...]|...],
%@ N = 72.
``````

What I can see, your code is correct; it should be the 8 solutions your program generates. (Where have you read that it should be 72 solutions for a 3x3 magic square? )

Note that with symmetry breaking (rotated, transposed, or flipped) there is just one solution of a 3x3 magic square. This is when it is in the Frénicle standard form (Frénicle standard form - Wikipedia):

``````1. the element at position [1,1] (top left corner) is the smallest of the four corner elements; and
2. the element at position [1,2] (top edge, second from left) is smaller than the element in [2,1].
``````

(For more on magic squares, see Magic square - Wikipedia )

Oh, I see…

@kuniaki.mukai and @hakank are right in their observations.
It turns out that there are many kinds of magic squares, and the diagonal constraints make a great difference…
I’m glad I didn’t do anything wrong. Next time I will study the underlying theory more carefully BEFORE coding…

Thank you very much for your assistance!