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

A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12).

This means that the subsquares also have an even size, which plays a role in the construction.



1
2
62
61
60
59
7
8


9
10
54
53
52
51
15
16


48
47
19
20
21
22
42
41


40
39
27
28
29
30
34
33


32
31
35
36
37
38
26
25


24
23
43
44
45
46
18
17


49
50
14
13
12
11
55
56


57
58
6
5
4
3
63
64



Task
Create a magic square of   8 × 8.



Related tasks
 Magic squares of odd order
 Magic squares of singly even order



See also

 Doubly Even Magic Squares (1728.org)


with javascript_semantics
constant t = {{1,1,0,0},
              {1,1,0,0},
              {0,0,1,1},
              {0,0,1,1}}
 
function magic_square(integer n)
    if n<4 or mod(n,4)!=0 then return false end if
    sequence square = repeat(repeat(0,n),n)
    integer i = 0
    for r=1 to n do
        for c=1 to n do
            square[r,c] = iff(t[mod(r,4)+1,mod(c,4)+1]?i+1:n*n-i)
            i += 1
        end for
    end for
    return square
end function
 
procedure check(sequence sq)
    integer n = length(sq)
    integer magic = n*(n*n+1)/2
    integer bd = 0, fd = 0
    for i=1 to length(sq) do
        if sum(sq[i])!=magic then ?9/0 end if
        if sum(columnize(sq,i))!=magic then ?9/0 end if
        bd += sq[i,i]
        fd += sq[n-i+1,n-i+1]
    end for
    if bd!=magic or fd!=magic then ?9/0 end if
end procedure
 
--for i=4 to 16 by 4 do
for i=8 to 8 by 4 do
    sequence square = magic_square(i)
    printf(1,"maqic square of order %d, sum: %d\n", {i,sum(square[i])})
    string fmt = sprintf("%%%dd",length(sprintf("%d",i*i)))
    pp(square,{pp_Nest,1,pp_IntFmt,fmt,pp_StrFmt,3,pp_IntCh,false,pp_Pause,0})
    check(square)
end for
