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)


Procedure.i MagicN(n.i)
  ProcedureReturn n*(n*n+1)/2
EndProcedure
 
Procedure.i MaxN(mx.i,n.i)
  If mx>n : ProcedureReturn mx : Else : ProcedureReturn n : EndIf
EndProcedure
 
Procedure.i MaxL(mx.i)
  Define.i i
  While mx
    mx/10 : i+1
  Wend
  ProcedureReturn i
EndProcedure
 
Procedure.b DblEvenMagicSquare(n.i)
  Define.i q=n/4, nr=1, x, y, max, spc
  Dim sq.i(n,n)
 
  For y=1 To n
    For x=q+1 To n-q
      sq(x,y)=1
    Next
  Next
 
  For x=1 To n
    For y=q+1 To n-q
      sq(x,y) ! 1
    Next
  Next
 
  q=n*n+1
  For y=1 To n
    For x=1 To n
      If sq(x,y)=0
        sq(x,y)=q-nr
      Else
        sq(x,y)=nr
      EndIf
      nr+1
      max=MaxN(max,sq(x,y))
    Next
  Next
 
  spc=MaxL(max)+1
  For y=n To 1 Step -1
    For x=n To 1 Step -1
      Print(RSet(Str(sq(x,y)),spc," "))
    Next
    PrintN("")
  Next
 
EndProcedure
 
OpenConsole("Magic-Square-Doubly-Even")
Define.i n
 
Repeat
  PrintN("Input [4,8,12..n] (0=Exit)")
  While (n<4) Or (n%4)
    Print(">") : n=Val(Input())
    If n=0 : End : EndIf
  Wend  
  PrintN("The magic sum = "+Str(MagicN(n)))
  DblEvenMagicSquare(n)  
  n=0
ForEver