Magic squares of singly even order: Difference between revisions

Add C# implementation
(→‎{{header|Haskell}}: Added comments)
(Add C# implementation)
 
(48 intermediate revisions by 20 users not shown)
Line 16:
* [http://www.1728.org/magicsq3.htm Singly Even Magic Squares (1728.org)]<br><br>
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">-V LOG_10 = 2.302585092994
 
F build_oms(=s)
I s % 2 == 0
s++
V q = [[0] * s] * s
V p = 1
V i = s I/ 2
V j = 0
 
L p <= (s * s)
q[i][j] = p
V ti = i + 1
I ti >= s
ti = 0
V tj = j - 1
I tj < 0
tj = s - 1
I q[ti][tj] != 0
ti = i
tj = j + 1
i = ti
j = tj
p++
 
R (q, s)
 
F build_sems(=s)
I s % 2 == 1
s++
L s % 4 == 0
s += 2
V q = [[0] * s] * s
V z = s I/ 2
V b = z * z
V c = 2 * b
V d = 3 * b
V o = build_oms(z)
 
L(j) 0 .< z
L(i) 0 .< z
V a = o[0][i][j]
q[i][j] = a
q[i + z][j + z] = a + b
q[i + z][j] = a + c
q[i][j + z] = a + d
 
V lc = z I/ 2
V rc = lc
L(j) 0 .< z
L(i) 0 .< s
I i < lc
| i > s - rc
| (i == lc & j == lc)
I !(i == 0 & j == lc)
swap(&q[i][j], &q[i][j + z])
R (q, s)
 
F display(q)
V s = q[1]
print(" - #. x #.\n".format(s, s))
V k = 1 + Int(floor(log(s * s) / :LOG_10))
L(j) 0 .< s
L(i) 0 .< s
print(String(q[0][i][j]).zfill(k), end' ‘ ’)
print()
print(‘Magic sum: #.’.format(s * ((s * s) + 1) I/ 2))
 
print(‘Singly Even Magic Square’, end' ‘’)
display(build_sems(6))</syntaxhighlight>
 
{{out}}
<pre>
Singly Even Magic Square - 6 x 6
 
35 01 06 26 19 24
03 32 07 21 23 25
31 09 02 22 27 20
08 28 33 17 10 15
30 05 34 12 14 16
04 36 29 13 18 11
Magic sum: 111
</pre>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Magic squares of singly even order - 21/04/2021
MAGSQSE CSECT
USING MAGSQSE,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LH R2,N n
MH R2,N *n
LA R2,1(R2) +1
MH R2,N *n
SRA R2,1 /2
STH R2,MAGSUM magsum=n*(n^2+1)/2
LH R2,N n
SRA R2,1 /2
STH R2,ND nd=n/2
LH R2,ND n
MH R2,ND *n
STH R2,ND2 nd2=nd^2
LH R2,N n
SH R2,=H'2' -2
SRA R2,2 /4
STH R2,LL ll=(n-2)/4
LH R6,ND nd
SRA R6,1 /2
LA R6,1(R6) i=nd/2+1
LA R7,1 j=1
LR R5,R7 nr=1
LH R4,N n
IF CH,R4,LT,=H'6' THEN if n<6 then
XPRNT =C'Error: too small',16
B FIN stop
ENDIF , endif
LH R2,N n
SH R2,=H'2' -2
SRDA R2,32 ~
D R2,=F'4' /4
IF LTR,R2,NZ,R2 THEN if mod(n-2,4)<>0 then
XPRNT =C'Error: not possible',19
B FIN stop
ENDIF , endif
LOOP EQU * do loop --------------v
LR R1,R6 i
LR R2,R7 j
BAL R14,SQXY r1=@sq(i,j)
LH R2,SQ(R1) sq(i,j)
IF LTR,R2,Z,R2 THEN if sq(i,j)=0 then
STH R5,SQ(R1) sq(i,j)=nr _A
LR R1,R6 i
AH R1,ND +nd
LR R2,R7 j
AH R2,ND +nd
BAL R14,SQXY r1=@sq(i+nd,j+nd)
LR R3,R5 nr
AH R3,ND2 +nd2
STH R3,SQ(R1) sq(i+nd,j+nd)=nr+nd2 _B
LR R1,R6 i
AH R1,ND +nd
LR R2,R7 j
BAL R14,SQXY r1=@sq(i+nd,j)
LH R3,ND2 nd2
SLA R3,1 *2
AR R3,R5 +nr
STH R3,SQ(R1) sq(i+nd,j)=nr+nd2*2; _C
LR R1,R6 i
LR R2,R7 j
AH R2,ND +nd
BAL R14,SQXY r1=@sq(i,j+nd)
LH R3,ND2 nd2
MH R3,=H'3' *3
AR R3,R5 +nr
STH R3,SQ(R1) sq(i,j+nd)=nr+nd2*3; _D
LR R2,R5 nr
LH R0,ND nd
SRDA R2,32 ~
DR R2,R0 nr/nd
IF LTR,R2,Z,R2 THEN if mod(nr,nd)=0 then
LA R7,1(R7) j=j+1
ELSE , else
LA R6,1(R6) i=i+1
BCTR R7,0 j=j-1
ENDIF , endif
LA R5,1(R5) nr=nr+1
ENDIF , endif
IF CH,R6,GT,ND THEN if i>nd then
LA R6,1 i=1
BAL R12,SQIJ r2=sq(i,j)
DO WHILE=(LTR,R2,NZ,R2) do while sq(i,j)<>0
LA R6,1(R6) i=i+1
BAL R12,SQIJ r2=sq(i,j)
ENDDO , enddo
ENDIF , endif
IF CH,R7,LT,=H'1' THEN if j<1 then
LH R7,ND j=nd
BAL R12,SQIJ r2=sq(i,j)
DO WHILE=(LTR,R2,NZ,R2) do while sq(i,j)<>0
BCTR R7,0 j=j-1
BAL R12,SQIJ r2=sq(i,j)
ENDDO , enddo
ENDIF , endif
CH R5,ND2 nr>nd2
BNH LOOP until nr>nd2 ---------^
LA R7,1 j=1 -- swap left side
DO WHILE=(CH,R7,LE,ND) do j=1 to nd
LA R6,1 i=1
DO WHILE=(CH,R6,LE,LL) do i=1 to ll
BAL R12,SWAPIJ swap sq(i,j),sq(i,j+nd)
LA R6,1(R6) i++
ENDDO , enddo i
LA R7,1(R7) j++
ENDDO , enddo j
LH R7,ND nd
SRA R7,1 /2
LA R7,1(R7) j=nd/2+1
LA R1,1 1
LR R2,R7 j
BAL R14,SQXY r1=@sq(1,j)
LR R3,R1 r3=@sq(1,j)
LA R1,1 1
LR R2,R7 j
AH R2,ND j+nd
BAL R14,SQXY r1=@sq(1,j+nd)
BAL R14,SWAPXY swap sq(1,j),sq(1,j+nd)
LH R1,LL ll
LA R1,1(R1) ll+1
LR R2,R7 j
BAL R14,SQXY r1=@sq(ll+1,j)
LR R3,R1 r3=@sq(ll+1,j)
LH R1,LL ll
LA R1,1(R1) +1
LR R2,R7 j
AH R2,ND +nd
BAL R14,SQXY r1=@sq(ll+1,j+nd)
BAL R14,SWAPXY swap sq(ll+1,j),sq(ll+1,j+nd)
LH R5,N n
SH R5,LL -ll
LA R5,2(R5) r5=n-ll+2
LA R7,1 j=1 -- swap right side
DO WHILE=(CH,R7,LE,ND) do j=1 to nd
LR R6,R5 i=n-ll+2
DO WHILE=(CH,R6,LE,N) do i=n-ll+2 to n
BAL R12,SWAPIJ swap sq(i,j),sq(i,j+nd)
LA R6,1(R6) i++
ENDDO , enddo i
LA R7,1(R7) j++
ENDDO , enddo j
LA R7,1 j=1 check columms and rows
DO WHILE=(CH,R7,LE,N) do j=1 to n
SR R4,R4 nr=0
SR R5,R5 nc=0
LA R6,1 i=1
DO WHILE=(CH,R6,LE,N) do i=1 to n
LR R1,R6 i
LR R2,R7 j
BAL R14,SQXY r1=@sq(i,j)
AH R4,SQ(R1) nr=nr+sq(i,j)
LR R1,R7 j
LR R2,R6 i
BAL R14,SQXY r1=@sq(j,i)
AH R5,SQ(R1) nc=nc+sq(j,i)
LA R6,1(R6) i++
ENDDO , enddo i
IF CH,R4,NE,MAGSUM,OR,CH,R5,NE,MAGSUM THEN
XPRNT =C'Error: row/col value<>magsum',28
B FIN stop
ENDIF , endif
LA R7,1(R7) j++
ENDDO , enddo j
SR R4,R4 nr=0
SR R5,R5 nc=0
LA R6,1 i=1
DO WHILE=(CH,R6,LE,N) do i=1 to n
LR R1,R6 i
LR R2,R6 i
BAL R14,SQXY r1=@sq(i,i)
AH R4,SQ(R1) nr=nr+sq(i,i)
LH R1,N n
SR R1,R6 n-i
LA R1,1(R1) n-i+1
LR R2,R1 n-i+1
BAL R14,SQXY r1=@sq(i,i)
AH R5,SQ(R1) nc=nc+sq(n-i+1,n-i+1)
LA R6,1(R6) i++
ENDDO , enddo i
IF CH,R4,NE,MAGSUM,OR,CH,R5,NE,MAGSUM THEN
XPRNT =C'Error: diag value<>magsum',25
B FIN stop
ENDIF , endif
MVC PG(31),=C'Single even magic square size: '
LH R1,N n
XDECO R1,XDEC edit n
MVC PG+31(3),XDEC+9 output n
XPRNT PG,34 print buffer
MVC PG(15),=C'The magic sum= '
LH R1,MAGSUM magsum
XDECO R1,XDEC edit magsum
MVC PG+15(4),XDEC+8 output magsum
XPRNT PG,19 print buffer
LA R7,1 j=1
DO WHILE=(CH,R7,LE,N) do j=1 to n
MVC PG,=CL120' ' clear buffer
LA R9,PG @buffer
LA R6,1 i=1
DO WHILE=(CH,R6,LE,N) do i=1 to n
LR R1,R6 i
LR R2,R7 j
BAL R14,SQXY r1=@sq(i,i)
LH R2,SQ(R1) sq(i,j)
XDECO R2,XDEC edit sq(i,j)
MVC 0(4,R9),XDEC+8 output sq(i,j)
LA R9,4(R9) @buffer+=4
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT PG,L'PG print buffer
LA R7,1(R7) j++
ENDDO , enddo j
FIN L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling save
SQIJ CNOP 0,4 routine sq(i,j)
LR R1,R6 i
LR R2,R7 j
BAL R14,SQXY r1=@sq(i,j)
LH R2,SQ(R1) sq(i,j)
BR R12 return
SQXY CNOP 0,4 routine sq(r1,r2)
BCTR R1,0 -1
MH R1,N *n
BCTR R2,0 -1
AR R1,R2 (r1-1)*n+(r2-1)
SLA R1,1 *2 (H)
BR R14 return
SWAPIJ CNOP 0,4 routine swap sq(i,j),sq(i,j+nd)
LR R1,R6 i
LR R2,R7 j
BAL R14,SQXY r1=@sq(i,j)
LR R3,R1 r3=@sq(i,j)
LR R1,R6 i
LR R2,R7 j
AH R2,ND +nd
BAL R14,SQXY r1=@sq(i,j+nd)
BAL R14,SWAPXY swap
BR R12 return
SWAPXY CNOP 0,4 routine swap sq(r1),sq(r3)
LH R0,SQ(R3) r0=sq(r3)
LH R2,SQ(R1) r2=sq(r1)
STH R2,SQ(R3) sq(r3)=r2
STH R0,SQ(R1) sq(r1)=r0
BR R14 return
NN EQU 6 <== parameter (6,10,14,18,22,26,...)
N DC AL2(NN) n
SQ DC (NN*NN)H'0' array sq(n,n)
MAGSUM DS H magsum
ND DS H nd
ND2 DS H nd2
LL DS H ll
PG DC CL120' ' buffer
XDEC DS CL12 temp for xdeco
REGEQU
END MAGSQSE</syntaxhighlight>
{{out}}
<pre>
Single even magic square size: 6
The magic sum= 111
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
</pre>
 
=={{header|ALGOL 68}}==
{{Trans|Jave|with odd magic square code from the Algol 68 sample of the Magic squares of odd order task}}
<syntaxhighlight lang="algol68">
BEGIN # construct a magic square of singly even order #
# the singly even magic square procedure is translated from the Java #
# sample #
 
CO begin code from the magic squares of odd order task CO
 
# construct a magic square of odd order #
PROC odd magic square = ( INT order ) [,]INT:
IF NOT ODD order OR order < 1 THEN
# can't make a magic square of the specified order #
LOC[ 1 : 0, 1 : 0 ]INT
ELSE
# order is OK - construct the square using de la Loubère's #
# algorithm as in the wikipedia page #
 
[ 1 : order, 1 : order ]INT square;
FOR i TO order DO FOR j TO order DO square[ i, j ] := 0 OD OD;
 
# operator to advance "up" the square #
OP PREV = ( INT pos )INT: IF pos = 1 THEN order ELSE pos - 1 FI;
# operator to advance "across right" or "down" the square #
OP NEXT = ( INT pos )INT: ( pos MOD order ) + 1;
 
# fill in the square, starting from the middle of the top row #
INT col := ( order + 1 ) OVER 2;
INT row := 1;
FOR i TO order * order DO
square[ row, col ] := i;
IF square[ PREV row, NEXT col ] /= 0 THEN
# the up/right position is already taken, move down #
row := NEXT row
ELSE
# can move up and right #
row := PREV row;
col := NEXT col
FI
OD;
 
square
FI # odd magic square # ;
 
PROC print square = ( [,]INT square )VOID: # prints the magic square #
BEGIN
 
INT order = 1 UPB square;
 
# calculate print width: negative so leading "+"s aren't printed #
INT width := -1;
INT mag := order * order;
WHILE mag >= 10 DO mag OVERAB 10; width -:= 1 OD;
 
# calculate the "magic sum" #
INT sum := 0;
FOR i TO order DO sum +:= square[ 1, i ] OD;
 
# print the square #
print( ( "maqic square of order ", whole( order, 0 ) ) );
print( ( ": sum: ", whole( sum, 0 ), newline ) );
FOR i TO order DO
FOR j TO order DO write( ( " ", whole( square[ i, j ], width ) ) ) OD;
print( ( newline ) )
OD
 
END # print square # ;
 
CO end code from the magic squares of odd order task CO
 
# returns a magic square of singly even order n #
PROC singly even magic square = ( INT n )[,]INT:
IF n < 6 OR ( n - 2 ) MOD 4 /= 0 THEN
LOC[ 1 : 0, 1 : 0 ]INT # n is not 2 + a multiple of 4 >= 6 #
ELSE
# order is OK #
INT size = n * n;
INT half n = n OVER 2;
INT sub square size = size OVER 4;
 
[,]INT sub square = odd magic square( half n )[ AT 0, AT 0 ];
[]INT quadrant factors = []INT( 0, 2, 3, 1 )[ AT 0 ];
[ 0 : n - 1, 0 : n - 1 ]INT result;
 
FOR r FROM 1 LWB result TO 1 UPB result DO
FOR c FROM 2 LWB result TO 2 UPB result DO
INT quadrant = ( r OVER half n ) * 2 + ( c OVER half n );
result[ r, c ] := sub square[ r MOD half n, c MOD half n ]
+ quadrant factors[ quadrant ] * sub square size
OD
OD;
 
INT n cols left = half n OVER 2;
INT n cols right = n cols left - 1;
 
FOR r FROM 1 LWB result TO half n - 1 DO
FOR c FROM 1 LWB result TO 1 UPB result DO
IF c < n cols left OR c >= n - n cols right
OR ( c = n cols left AND r = n cols left )
THEN
IF c /= 0 OR r /= n cols left THEN
INT tmp = result[ r, c ];
result[ r, c ] := result[ r + half n, c ];
result[ r + half n, c ] := tmp
FI
FI
OD
OD;
 
result[ AT 1, AT 1 ]
FI # singly even magic square # ;
 
print square( singly even magic square( 6 ) )
 
END
</syntaxhighlight>
{{out}}
<pre>
maqic square of order 6: sum: 111
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
</pre>
 
=={{header|Befunge}}==
The size, ''N'', is specified by the first value on the stack. In the example below it is set to 6, but adequate space has been left in the code to replace that with a larger value if desired.
 
<syntaxhighlight lang="befunge">6>>>>>:00p:2/vv1:%g01p04:%g00::p03*2%g01/g00::-1_@
\00g/10g/3*4vv>0g\-1-30g+1+10g%10g*\30g+1+10g%1+ +
:%4+*2/g01g0<vv4*`\g02\!`\0:-!-g02/2g03g04-3*2\-\3
*:p02/4-2:p01<>0g00g20g-`+!!*+10g:**+.:00g%!9+,:^:</syntaxhighlight>
 
{{out}}
<pre>26 19 24 8 1 33
21 23 25 3 32 7
22 27 20 4 9 29
17 10 15 35 28 6
12 14 16 30 5 34
13 18 11 31 36 2</pre>
 
=={{header|C}}==
Takes number of rows from command line, prints out usage on incorrect invocation.
<syntaxhighlight lang="c">
#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** oddMagicSquare(int n) {
if (n < 3 || n % 2 == 0)
return NULL;
int value = 0;
int squareSize = n * n;
int c = n / 2, r = 0,i;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
while (++value <= squareSize) {
result[r][c] = value;
if (r == 0) {
if (c == n - 1) {
r++;
} else {
r = n - 1;
c++;
}
} else if (c == n - 1) {
r--;
c = 0;
} else if (result[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
return result;
}
int** singlyEvenMagicSquare(int n) {
if (n < 6 || (n - 2) % 4 != 0)
return NULL;
int size = n * n;
int halfN = n / 2;
int subGridSize = size / 4, i;
int** subGrid = oddMagicSquare(halfN);
int gridFactors[] = {0, 2, 3, 1};
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int grid = (r / halfN) * 2 + (c / halfN);
result[r][c] = subGrid[r % halfN][c % halfN];
result[r][c] += gridFactors[grid] * subGridSize;
}
}
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
for (int r = 0; r < halfN; r++)
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight
|| (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft)
continue;
int tmp = result[r][c];
result[r][c] = result[r + halfN][c];
result[r + halfN][c] = tmp;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j;
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2);
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(singlyEvenMagicSquare(n),n);
}
return 0;
}
</syntaxhighlight>
Invocation and Output:
<pre>
C:\rosettaCode>singlyEvenMagicSquare 6
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
 
Magic constant: 111
</pre>
 
=={{header|C#}}==
{{trans|Go}}
<syntaxhighlight lang="C#">
using System;
 
class MagicSquare {
public static int[,] MagicSquareOdd(int n) {
if (n < 3 || n % 2 == 0) {
throw new ArgumentException("Base must be odd and > 2");
}
int value = 1;
int gridSize = n * n;
int c = n / 2, r = 0;
int[,] result = new int[n, n];
 
while (value <= gridSize) {
result[r, c] = value;
int newR = r == 0 ? n - 1 : r - 1;
int newC = c == n - 1 ? 0 : c + 1;
if (result[newR, newC] != 0) {
r++;
} else {
r = newR;
c = newC;
}
value++;
}
 
return result;
}
 
public static int[,] MagicSquareSinglyEven(int n) {
if (n < 6 || (n - 2) % 4 != 0) {
throw new ArgumentException("Base must be a positive multiple of 4 plus 2");
}
 
int size = n * n;
int halfN = n / 2;
int subSquareSize = size / 4;
int[,] subSquare = MagicSquareOdd(halfN);
int[] quadrantFactors = new int[] {0, 2, 3, 1};
int[,] result = new int[n, n];
 
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int quadrant = (r / halfN) * 2 + (c / halfN);
result[r, c] = subSquare[r % halfN, c % halfN] + quadrantFactors[quadrant] * subSquareSize;
}
}
 
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
 
for (int r = 0; r < halfN; r++) {
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) {
if (!(c == 0 && r == nColsLeft)) {
int tmp = result[r, c];
result[r, c] = result[r + halfN, c];
result[r + halfN, c] = tmp;
}
}
}
}
 
return result;
}
 
static void Main(string[] args) {
const int n = 6;
try {
var msse = MagicSquareSinglyEven(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Console.Write($"{msse[i, j],2} ");
}
Console.WriteLine();
}
Console.WriteLine($"\nMagic constant: {(n * n + 1) * n / 2}");
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
</syntaxhighlight>
{{out}}
<pre>
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
 
Magic constant: 111
 
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <sstream>
Line 128 ⟶ 864:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 144 ⟶ 880:
=={{header|D}}==
{{trans|Java}}
<syntaxhighlight lang="d">
<lang d>
import std.exception;
import std.stdio;
Line 231 ⟶ 967:
return result;
}
</syntaxhighlight>
</lang>
 
=={{header|EDSAC order code}}==
This method for constructing singly-even magic squares is due to Ralph Strachey and appears in W.W. Rouse Ball's "Mathematical Recreations and Essays" (e.g. 11th edn, pp 196-199; or see the link in the J solution). Because array handling on EDSAC is so awkward, it seems better not to store the magic square entries but to print each entry as it is calculated. With Strachey's algorithm this becomes easier if the square is rotated 90 degrees clockwise from Ball's description. Apart from that, the 6x6 and 10x10 squares generated by the program agree with those given by Ball.
<syntaxhighlight lang="edsac">
[Magic squares of singly even order, for Rosetta Code.
EDSAC program, Initial Orders 2.]
[=============================================================================]
[Uses Strachey's method, but with the square rotated 90 degrees clockwise.
Let the side be 2q. The square is divided into 4 quadrants each of side q.
In each quadrant, a 0-based magic square is created by De la Loubere's rule.
The final square is got by adding k*q^2 + 1 to each entry, where 0 <= k <= 3.]
[=============================================================================]
[Arrange the storage]
T45K P56F [H parameter: subroutine to print string]
T46K P100F [N parameter: subroutine to print number]
T47K P200F [M parameter: main routine]
[Main routine]
E25K TM GK
[Variables]
[0] PF [m, where side of square = 4*m + 2]
[1] PF [q = side of a quadrant = 2*m + 1]
[2] PF [q^2]
[3] PF [negative counter for columns]
[4] PF [negative counter for rows]
[5] PF [q*u for De la Loubere's method]
[6] PF [v for De la Loubere's method]
[7] PF [value of q*u at start of row]
[8] PF [ditto v]
[9] PF [add-on k*q^2 + 1 for left half of row]
[10] PF [add-on k*q^2 + 1 for right half of row]
[In the top two quadrants, the left and right add-ons are swapped for
"special" cells: (1) centre cell of top row (2) centre cell of quadrant.]
[11] PF [EDSAC null if left & right add-ons are to be swapped; else 0]
[12] PF [value of current special cell]
[Constants]
[13] K4096F [EDSAC null, i.e. 10000000000000000 binary]
[14] !F [space]
[15] @F [carriage return]
[16] &F [line feed]
[17] PD [17-bit constant 1]
[18] P10F [10 in address field (test for '0' on phone dial)]
[Strings, terminated by EDSAC null]
[19] K2048FMFAFGFIFCF!FSFQFUFAFRFEF!FOFFF!FOFRFDFEFRF!F#FRF*FMF#FZFWF@F&FK4096F
[52] K2048FDFIFAFLF!FMF!F#FKFPF!F*FTFOF!FCFAFNFCFEFLF#FLF!FK4096F
[78] K2048FSFTFRFAFCFHFEFYF!F#FKF*FRFOFTFAFTFEFDF#FLFCF@F&FK4096F
[Enter with acc = 0]
[104] A104@ GH A19@ [print header: says side of square = 4*m + 2]
[107] A107@ GH A52@ [prompt user to enter m on phone dial]
ZF [halt machine, restarts when user dials]
[Here acc holds number of pulses in address field]
S18@ [test wheter user dialled '0' (10 pulses)]
E183@ [jump to exit if so]
A18@ [restore acc after test]
L512F UF [shift 11 left, to 0F for printing]
OF O15@ O16@ [print m followed by CR, LF]
R512F [shift back 11 right; acc = 2m right-justified]
A17@ U1@ [store q = 2m + 1 = n/2, right justified]
RD T@ [shift 1 right, store m right-justified]
H1@ V1@ [acc := q^2]
L64F L64F [16 left to adjust scaling after mult.]
T2@ [store q^2]
[129] A129@ GH A78@ [print 'STRACHEY (ROTATED):']
A14@ T1F [use space for leading zeros when printing]
[In each quadrant, use De la Loubere's method. 0-based entry is q*u + v
where u, v are digits in base q. Example for m = 2, q = 2*m + 1 = 5:
u = 2 1 0 4 3 v = 0 4 3 2 1 At top left, u = m, v = 0
3 2 1 0 4 2 1 0 4 3 Moving right, u and v decrease by 1 mod q
4 3 2 1 0 4 5 2 1 0 Moving down, u increases by 1 mod q
0 4 3 2 1 1 0 4 3 2 v increases by 2 mod q
1 0 4 3 2 3 2 1 0 4]
H1@ V@ [acc := q*m]
L64F L64F [16 left to adjust integer scaling scaling after mult.]
T7@ [store q*u at start of top row]
T8@ [v at start of top row := 0]
[At the start of each stage, set counter to m - (number of rows in that stage)]
[Stage 1, m rows]
T4@ [counter := 0]
A17@ T9@ [add-on for left half of row = 1]
A2@ LD A2@ [acc := 3*q^2]
A17@ T10@ [add-on for right half of row = 3q^2 + 1]
[Special cell is centre of top row; value is m + 1]
A@ A17@ T12@ [special pass m + 1 to subroutine]
[151] A151@ G185@ [call subroutine to do stage 1]
[Stage 2, m + 1 rows]
S17@ T4@ [counter := -1]
A10@ T9@ [add-on for left half of row = 3q^2 + 1]
A17@ T10@ [add-on for right half of row = 1]
[Special cell is at centre of quadrant; value id (q^2 - 1)/2]
A2@ RD T12@ [shift q^2 1 right to get value (since q is pdd)]
[162] A162@ G185@ [call subroutine to do stage 2]
[Stage 3, m + 2 rows. Here acc = 0.]
S2F T4@ [counter := -2]
A9@ S2@ U10@ [add-on for right half of row = 2q^2 + 1]
S2@ T9@ [add-on for left half of row = q^2 + 1]
S17@ T12@ [no special cell (value < 0) in stages 3 & 4]
[173] A173@ G185@ [call subroutine to do stage 3]
[Stage 4, m - 1 rows]
A17@ T4@ [counter := 1]
A10@ U9@ [add-on for left half of row = 2q^2 + 1]
S2@ T10@ [add-on for right half of row = q^2 + 1]
[181] A181@ G185@ [call subroutine to do stage 4]
[183] O13@ [done; print null]
ZF [halt the machine]
[Subroutine to write the rows in one of the 4 stages.
Shares storage with the main routine.]
[185] A3F T256@ [plant return link as usual]
S@ [negative row counter := -m]
A4@ [plus adjustment set by caller]
E256@ [exit if nothing to do (happens for 6x6, stage 4)]
[190] T4@ [outer loop: update row counter]
[Start of a row. Goes across 2 quadrants.
Recall that 0-based entry is q*u + v where u, v are digits in base q]
S1@ LD T3@ [negative column counter := -2*q]
A7@ T5@ [reset q*u for start of row]
A8@ U6@ [same for v]
[Next column. Here acc contains v (the second digit)]
[198] A5@ [inner loop: add q*u where u = first digit]
T4F [park 0-based entry in 4F]
[Add on an amount depending on whether it's left or right quadrant.
In stages 1 and 2, the left and right add-ons are swapped for certain cells.]
T11@ [say not swapped]
A12@ [load special cell if any]
G210@ [jump if none (value < 0)]
S4F [compare with cell entry]
G210@ S17@ E210@ [jump if different]
TF A13@ T11@ [set flag in sign bit to reverse comparison]
[210] TF [clear acc]
A3@ A1@ [test for left or right quadrant]
A11@ [reverse test if flag was set above]
E218@ [jump if right quadrant]
TF [clear acc]
A9@ [load add-on for left quadrant]
E220@ [join common code]
[218] TF [clear acc]
A10@ [load add-on for right quadrant]
[220] A4F TF [common: final value of entry to 0F for printing]
[222] A222@ GN [print]
A3@ A17@ [inc negative column count]
E239@ [jump if row is complete]
T3@ [update column count]
[Next cell in row]
A5@ S1@ E232@ [dec q*u by q, skip if result >= 0]
A2@ [else wrap round by adding q^2]
[232] T5@ [update q*u]
A6@ S17@ E237@ [dec v by 1, skip if result >= 0]
A1@ [else wrap round by adding q]
[237] U6@ [update v, keep new v in acc]
E198@ [loop back]
[Here when row finished]
[239] O15@ O16@ [print CR, LF]
A7@ A1@ [update value of u at start of row]
S2@ E246@ [if >= q^2 then subtract q^2]
A2@ [else restore acc after test]
[246] T7@ [update value mod q^2]
A8@ A2F [similarly inc v mod q]
S1@ E252@ A1@
[252] T8@
A4@ A17@ G190@ [inc negative row count, loop till done]
[256] ZF [(planted) jump back to caller]
 
[Subroutine to print a string.
Input: A order for first character must follow subroutine call.
String is terminated with EDSAC null, which is sent to the teleprinter.]
E25K TH
GKA18@U17@S19@T4@AFT6@AFUFOFE12@A20@G16@TFA6@A2FG5@TFZFU3FU1FK2048F
 
[Subroutine to print non-negative 17-bit integer.
Parameters: 0F = integer to be printed (not preserved)
1F = character for leading zero (preserved)
Workspace: 4F..7F, 38 locations]
E25K TN
GKA3FT34@A1FT7FS35@T6FT4#FAFT4FH36@V4FRDA4#FR1024FH37@E23@O7FA2F
T6FT5FV4#FYFL8FT4#FA5FL1024FUFA6FG16@OFTFT7FA6FG17@ZFP4FZ219DTF
 
[================ M parameter again ================]
E25K TM GK
E104Z [define entry point]
PF [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
MAGIC SQUARE OF ORDER 4M+2
DIAL M (0 TO CANCEL) 1
STRACHEY (ROTATED):
4 30 8 31 3 35
36 5 28 9 32 1
29 34 33 2 7 6
13 12 17 22 21 26
18 14 10 27 23 19
11 16 15 20 25 24
MAGIC SQUARE OF ORDER 4M+2
DIAL M (0 TO CANCEL) 2
STRACHEY (ROTATED):
11 10 79 23 17 86 85 4 98 92
18 12 6 5 24 93 87 81 80 99
100 94 13 82 76 25 19 88 7 1
77 96 95 89 83 2 21 20 14 8
84 78 97 91 90 9 3 22 16 15
36 35 29 48 42 61 60 54 73 67
43 37 31 30 49 68 62 56 55 74
50 44 38 32 26 75 69 63 57 51
27 46 45 39 33 52 71 70 64 58
59 53 72 66 65 34 28 47 41 40
</pre>
 
=={{header|Elixir}}==
[[wp:Conway's LUX method for magic squares]]:
<langsyntaxhighlight lang="elixir">defmodule Magic_square do
@lux %{ L: [4, 1, 2, 3], U: [1, 4, 2, 3], X: [1, 4, 3, 2] }
Line 282 ⟶ 1,222:
end
 
Magic_square.singly_even(6)</langsyntaxhighlight>
 
{{out}}
Line 295 ⟶ 1,235:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 18-03-2016
' compile with: fbc -s console
' singly even magic square 6, 10, 14, 18...
Line 441 ⟶ 1,381:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Single even magic square size: 6*6
Line 452 ⟶ 1,392:
30 5 34 12 14 16
4 36 29 13 18 11</pre>
 
=={{header|Go}}==
{{trans|Java}}
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"log"
)
 
func magicSquareOdd(n int) ([][]int, error) {
if n < 3 || n%2 == 0 {
return nil, fmt.Errorf("base must be odd and > 2")
}
value := 1
gridSize := n * n
c, r := n/2, 0
result := make([][]int, n)
 
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
 
for value <= gridSize {
result[r][c] = value
if r == 0 {
if c == n-1 {
r++
} else {
r = n - 1
c++
}
} else if c == n-1 {
r--
c = 0
} else if result[r-1][c+1] == 0 {
r--
c++
} else {
r++
}
value++
}
return result, nil
}
 
func magicSquareSinglyEven(n int) ([][]int, error) {
if n < 6 || (n-2)%4 != 0 {
return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2")
}
size := n * n
halfN := n / 2
subSquareSize := size / 4
subSquare, err := magicSquareOdd(halfN)
if err != nil {
return nil, err
}
quadrantFactors := [4]int{0, 2, 3, 1}
result := make([][]int, n)
 
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
 
for r := 0; r < n; r++ {
for c := 0; c < n; c++ {
quadrant := r/halfN*2 + c/halfN
result[r][c] = subSquare[r%halfN][c%halfN]
result[r][c] += quadrantFactors[quadrant] * subSquareSize
}
}
 
nColsLeft := halfN / 2
nColsRight := nColsLeft - 1
 
for r := 0; r < halfN; r++ {
for c := 0; c < n; c++ {
if c < nColsLeft || c >= n-nColsRight ||
(c == nColsLeft && r == nColsLeft) {
if c == 0 && r == nColsLeft {
continue
}
tmp := result[r][c]
result[r][c] = result[r+halfN][c]
result[r+halfN][c] = tmp
}
}
}
return result, nil
}
 
func main() {
const n = 6
msse, err := magicSquareSinglyEven(n)
if err != nil {
log.Fatal(err)
}
for _, row := range msse {
for _, x := range row {
fmt.Printf("%2d ", x)
}
fmt.Println()
}
fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2)
}</syntaxhighlight>
 
{{out}}
<pre>
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
 
Magic constant: 111
</pre>
 
=={{header|Haskell}}==
Using [[wp:Conway's LUX method for magic squares|Conway's LUX method for magic squares]]
<langsyntaxhighlight lang="haskell">import qualified Data.ListMap.Strict as M
import Data.List (mapAccumR, sortBy, groupBy, transpose, intercalate)
import Data.Maybe (fromJust, isJust)
import Control.Monad (forM_)
import Data.Ord (comparing)
import Data.Function (on)
import Data.Monoid ((<>))
 
magic :: Int -> [[Int]]
magic n = mapAsTable ((4 * n) + 2) (hiResMap n)
magic n =
let d = (2 * n) + 1
in threadRows . concat . snd $
mapAccumR
(\a (xy, c) -> (a + 4, luxNums xy c a))
1
(luxPath (luxPattern n) (siamPath (d - 1) [(quot d 2, 0)]))
 
-- Order of square -> sequence numbers keyed by cartesian coordinates
-- Size required -> square of L U X cells with two mixed rows
luxPatternhiResMap :: Int -> [String]M.Map (Int, Int) Int
luxPatternhiResMap n =
let dmapLux = (2 *luxMap n) + 1
[ls, us]mapSiam = replicate (quot d 2) <$>siamMap "LU"n
in M.fromList $
[lRow, xRow] = replicate d <$> "LX"
foldMap
in replicate n lRow <> [ls <> ('U' : ls)] <> [us <> ('L' : us)] <>
replicate (n\(xy, - 1n) xRow->
luxNums xy (fromJust (M.lookup xy mapLux)) ((4 * (n - 1)) + 1))
 
(M.toList mapSiam)
-- Highest 0-based index of grid -> Siamese path so far -> full Siamese path
siamPath :: Int -> [(Int, Int)] -> [(Int, Int)]
siamPath uBound xs@((x, y):path) =
if y == uBound && x == quot uBound 2
then xs
else siamPath uBound (pathSucc (x, y) : xs)
where
pathSucc (x, y) =
let alt (a, b)
| a > uBound && b < 0 = (uBound, 1)
| a > uBound = (0, b)
| b < 0 = (a, uBound)
| elem (a, b) path = (a - 1, b + 2)
| otherwise = (a, b)
in alt (x + 1, y - 1)
 
-- LUX table -> coordinate list -> LUX-labelled coordinate list
luxPath :: [String] -> [(Int, Int)] -> [((Int, Int), Char)]
luxPath rows = fmap (\(x, y) -> ((x, y), (rows !! y) !! x))
 
-- LUX table coordinate -> L|U|X -> initial number -> 4 numbered coordinates
Line 509 ⟶ 1,541:
'X' -> [0, 3, 2, 1]
_ -> [0, 0, 0, 0]
 
-- Size of square -> integers keyed by coordinates -> rows of integers
mapAsTable :: Int -> M.Map (Int, Int) Int -> [[Int]]
mapAsTable nCols xyMap =
let axis = [0 .. nCols - 1]
in fmap (fromJust . flip M.lookup xyMap) <$>
(axis >>= \y -> [axis >>= \x -> [(x, y)]])
 
-- Dimension of LUX table -> LUX symbols keyed by coordinates
luxMap :: Int -> M.Map (Int, Int) Char
luxMap n =
(M.fromList . concat) $
zipWith
(\y xs -> (zipWith (\x c -> ((x, y), c)) [0 ..] xs))
[0 ..]
(luxPattern n)
 
-- LUX dimension -> square of L|U|X cells with two mixed rows
luxPattern :: Int -> [String]
luxPattern n =
let d = (2 * n) + 1
[ls, us] = replicate n <$> "LU"
[lRow, xRow] = replicate d <$> "LX"
in replicate n lRow <> [ls <> ('U' : ls)] <> [us <> ('L' : us)] <>
replicate (n - 1) xRow
 
-- Highest zero-based index of grid -> Siamese indices keyed by coordinates
siamMap :: Int -> M.Map (Int, Int) Int
siamMap n =
let uBound = (2 * n)
sPath uBound sMap (x, y) n =
let newMap = M.insert (x, y) n sMap
in if y == uBound && x == quot uBound 2
then newMap
else sPath uBound newMap (nextSiam uBound sMap (x, y)) (n + 1)
in sPath uBound (M.fromList []) (n, 0) 1
 
-- Highest index of square -> Siam xys so far -> xy -> next xy coordinate
nextSiam :: Int -> M.Map (Int, Int) Int -> (Int, Int) -> (Int, Int)
nextSiam uBound sMap (x, y) =
let alt (a, b)
| a > uBound && b < 0 = (uBound, 1) -- Top right corner ?
| a > uBound = (0, b) -- beyond right edge ?
| b < 0 = (a, uBound) -- above top edge ?
| isJust (M.lookup (a, b) sMap) = (a - 1, b + 2) -- already filled ?
| otherwise = (a, b) -- Up one, right one.
in alt (x + 1, y - 1)
 
-- LUX cell coordinate -> four coordinates at higher resolution
Line 516 ⟶ 1,595:
[col1, row1] = succ <$> [col, row]
in [(col, row), (col1, row), (col, row1), (col1, row1)]
 
-- Numbered sequence of coordinates -> ordered rows
threadRows :: [((Int, Int), Int)] -> [[Int]]
threadRows cells =
let row = snd . fst
col = fst . fst
in (fmap snd . sortBy (comparing col) <$>
groupBy (on (==) row) (sortBy (comparing row) cells))
 
-- TESTS ----------------------------------------------------------------------
Line 530 ⟶ 1,601:
where
diagonals = fmap (flip (zipWith (!!)) [0 ..]) . ((:) <*> (return . reverse))
h:t = sum <$> square <> transpose square <> diagonals square
h:t =
sum <$>
square ++ -- rows
transpose square ++ -- cols
diagonals square -- diagonals
 
table :: String -> [[String]] -> [String]
Line 550 ⟶ 1,617:
putStrLn $ unlines (table " " (fmap show <$> test))
print $ checked test
putStrLn ""</langsyntaxhighlight>
{{Out}}
<pre>32 29 4 1 24 21
Line 590 ⟶ 1,657:
 
(1379,True)</pre>
 
=={{header|J}}==
Using the Strachey method:
 
<syntaxhighlight lang="j">
odd =: i:@<.@-: |."0 1&|:^:2 >:@i.@,~
t =: ((*: * i.@4:) +"0 2 odd)@-:
l =: (f=:$~ # , #)@((<. , >.)@%&4 # (1: , 0:))
sh =: <:@-: * (bn=:-: # 2:) #: (2: ^ <.@%&4)
lm =: sh |."0 1 l
rm =: f@bn #: <:@(2: ^ <:@<.@%&4)
a =: ((-.@lm * {.@t) + lm * {:@t)
b =: ((-.@rm * 1&{@t) + rm * 2&{@t)
c =: ((rm * 1&{@t) + -.@rm * 2&{@t)
d =: ((lm * {.@t) + -.@lm * {:@t)
m =: (a ,"1 c) , d ,"1 b
</syntaxhighlight>
 
{{Out}}
<pre>
m 6
33 7 2 24 25 20
1 32 9 19 23 27
35 3 4 26 21 22
6 34 29 15 16 11
28 5 36 10 14 18
8 30 31 17 12 13
 
m 18
258 268 278 288 46 56 66 76 5 177 187 197 207 208 218 147 157 86
277 287 297 298 65 75 4 14 24 196 206 216 217 227 237 85 95 105
296 306 307 317 3 13 23 33 43 215 225 226 236 165 175 104 114 124
315 316 245 255 22 32 42 52 62 234 235 164 174 184 194 123 133 143
1 254 264 274 284 51 61 71 81 163 173 183 193 203 213 142 152 162
263 273 283 293 60 70 80 9 10 182 192 202 212 222 232 161 90 91
282 292 302 312 79 8 18 19 29 201 211 221 231 241 170 99 100 110
301 311 321 250 17 27 28 38 48 220 230 240 169 179 189 109 119 129
320 249 259 269 36 37 47 57 67 239 168 178 188 198 199 128 138 148
15 25 35 45 289 299 309 319 248 96 106 116 126 127 137 228 238 167
34 44 54 55 308 318 247 257 267 115 125 135 136 146 156 166 176 186
53 63 64 74 246 256 266 276 286 134 144 145 155 84 94 185 195 205
72 73 2 12 265 275 285 295 305 153 154 83 93 103 113 204 214 224
244 11 21 31 41 294 304 314 324 82 92 102 112 122 132 223 233 243
20 30 40 50 303 313 323 252 253 101 111 121 131 141 151 242 171 172
39 49 59 69 322 251 261 262 272 120 130 140 150 160 89 180 181 191
58 68 78 7 260 270 271 281 291 139 149 159 88 98 108 190 200 210
77 6 16 26 279 280 290 300 310 158 87 97 107 117 118 209 219 229
</pre>
 
Alternative implementation of the [[wp:Strachey_method_for_magic_squares|Strachey method]]:
 
<syntaxhighlight lang="j">odd=: i. |."_1&|:^:2 >:@i.@,~
strachey2=: (odd +/~ (0 2,:3 1) * *:)@-:
exchange=: (* -.) + (* |.)~
columns=: {: | i.
strachey3=: exchange (,:~1 0) * ((2%~1-~{:) > columns)@$
strachey4=: exchange (,:~0 1) * ((2%~1+{:)< columns)@$
strachey5=: exchange (,:~1 0) */ (i.@,~@{: e. ((]*0 1+[)-:@<:)@{:)@$
 
strachey=: [: ,/ [: ,./"3 strachey5 @ strachey4 @ strachey3 @ strachey2</syntaxhighlight>
 
{{out}}
<pre> strachey 6
28 5 9 19 23 27
8 30 4 26 21 22
33 7 2 24 25 20
1 32 36 10 14 18
35 3 31 17 12 13
6 34 29 15 16 11</pre>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class MagicSquareSinglyEven {
 
public static void main(String[] args) {
Line 676 ⟶ 1,812:
return result;
}
}</langsyntaxhighlight>
 
<pre>35 1 6 26 19 24
Line 686 ⟶ 1,822:
 
Magic constant: 111</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
 
'''Works with jq and gojq, the C and Go implementations of jq'''
<syntaxhighlight lang=jq>
def magicSquareOdd:
. as $n
| if ($n < 3 or $n%2 == 0) then "Base must be odd and > 2" | error
else ($n * $n) as $gridSize
| { value: 1,
c: (($n/2) | floor),
r: 0,
result: []}
| until (.value > $gridSize;
.result[.r][.c] = .value
| if .r == 0
then if (.c == $n - 1)
then .r += 1
else .r = ($n - 1) | .c += 1
end
elif (.c == $n - 1)
then .r += -1
| .c = 0
elif (.result[.r - 1][.c + 1] == null)
then .r += -1 | .c += 1
else .r += 1
end
| .value += 1 )
| .result
end ;
 
def magicSquareSinglyEven:
. as $n
| if ($n < 6 or ($n - 2) % 4 != 0)
then "Base must be a positive multiple of 4 plus 2" | error
else ($n * $n) as $size
| ($n / 2) as $halfN
| ($size / 4) as $subSquareSize
| ($halfN|magicSquareOdd) as $subSquare
| [0, 2, 3, 1] as $quadrantFactors
| reduce range(0; $n) as $r ({};
reduce range(0; $n) as $c (.;
((($r/$halfN)|floor) * 2 + (($c/$halfN)|floor)) as $quadrant
| .result[$r][$c] = $subSquare[$r % $halfN][$c % $halfN]
| .result[$r][$c] += $quadrantFactors[$quadrant] * $subSquareSize ) )
| (($halfN/2)|floor) as $nColsLeft
| ($nColsLeft - 1) as $nColsRight
| reduce range(0; $halfN) as $r (.;
reduce range(0; $n) as $c (.;
if ($c < $nColsLeft or $c >= $n - $nColsRight or ($c == $nColsLeft and $r == $nColsLeft))
then if ($c != 0 or $r != $nColsLeft)
then .result[$r][$c] as $tmp
| .result[$r][$c] = .result[$r + $halfN][$c]
| .result[$r + $halfN][$c] = $tmp
else .
end
else .
end ) )
| .result
end ;
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
def task(n):
"Magic constant: \((n * n + 1) * n / 2)\n",
(n|magicSquareSinglyEven[] | map(lpad(3))|join(" ") );
 
task(6)
</syntaxhighlight>
{{output}}
<pre>
Magic constant: 111
 
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
</pre>
 
=={{header|Julia}}==
{{trans|Lua}}
<syntaxhighlight lang="julia">function oddmagicsquare(order)
if iseven(order)
order += 1
end
q = zeros(Int, (order, order))
p = 1
i = div(order, 2) + 1
j = 1
while p <= order * order
q[i, j] = p
ti = (i + 1 > order) ? 1 : i + 1
tj = (j - 1 < 1) ? order : j - 1
if q[ti, tj] != 0
ti = i
tj = j + 1
end
i = ti
j = tj
p = p + 1
end
q, order
end
 
function singlyevenmagicsquare(order)
if isodd(order)
order += 1
end
if order % 4 == 0
order += 2
end
q = zeros(Int, (order, order))
z = div(order, 2)
b = z * z
c = 2 * b
d = 3 * b
sq, ord = oddmagicsquare(z)
 
for j in 1:z, i in 1:z
a = sq[i, j]
q[i, j] = a
q[i + z, j + z] = a + b
q[i + z, j] = a + c
q[i, j + z] = a + d
end
lc = div(z, 2)
rc = lc - 1
for j in 1:z, i in 1:order
if i <= lc || i > order - rc || (i == lc && j == lc)
if i != 0 || j != lc + 1
t = q[i, j]
q[i, j] = q[i, j + z]
q[i, j + z] = t
end
end
end
q, order
end
 
function check(q)
side = size(q)[1]
sums = Vector{Int}()
for n in 1:side
push!(sums, sum(q[n, :]))
push!(sums, sum(q[:, n]))
end
println(all(x->x==sums[1], sums) ?
"Checks ok: all sides add to $(sums[1])." : "Bad sum.")
end
 
function display(q)
r, c = size(q)
for i in 1:r, j in 1:c
nstr = lpad(string(q[i, j]), 4)
print(j % c > 0 ? nstr : "$nstr\n")
end
end
 
for o in (6, 10)
println("\nWith order $o:")
msq = singlyevenmagicsquare(o)[1]
display(msq)
check(msq)
end
</syntaxhighlight> {{output}}<pre>
With order 6:
35 30 31 8 3 4
1 5 9 28 32 36
6 7 2 33 34 29
26 21 22 17 12 13
19 23 27 10 14 18
24 25 20 15 16 11
Checks ok: all sides add to 111.
 
With order 10:
92 98 79 85 86 17 23 4 10 11
99 80 81 87 93 24 5 6 12 18
1 7 13 19 25 76 82 88 94 100
8 14 20 21 2 83 89 95 96 77
15 16 22 3 9 90 91 97 78 84
67 73 54 60 61 42 48 29 35 36
74 55 56 62 68 49 30 31 37 43
51 57 63 69 75 26 32 38 44 50
58 64 70 71 52 33 39 45 46 27
40 41 47 28 34 65 66 72 53 59
Checks ok: all sides add to 505.
</pre>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun magicSquareOdd(n: Int): Array<IntArray> {
Line 758 ⟶ 2,084:
}
println("\nMagic constant ${(n * n + 1) * n / 2}")
}</langsyntaxhighlight>
 
{{out}}
Line 776 ⟶ 2,102:
See [[Magic_squares/Lua]].
 
=={{header|Perl 6Nim}}==
{{trans|Kotlin}}
See [[Magic_squares/Perl_6|Magic squares/Perl 6]] for a general magic square generator.
<syntaxhighlight lang="nim">import sequtils, strutils
 
type Square = seq[seq[int]]
 
func magicSquareOdd(n: Positive): Square =
## Build a magic square of odd order.
 
assert n >= 3 and (n and 1) != 0, "base must be odd and greater than 2."
result = newSeqWith(n, newSeq[int](n))
 
var
r = 0
c = n div 2
value = 0
 
while value < n * n:
inc value
result[r][c] = value
if r == 0:
if c == n - 1:
inc r
else:
r = n - 1
inc c
elif c == n - 1:
dec r
c = 0
elif result[r - 1][c + 1] == 0:
dec r
inc c
else:
inc r
 
 
func magicSquareSinglyEven(n: int): Square =
## Build a magic square of singly even order.
 
assert n >= 6 and ((n - 2) and 3) == 0, "base must be a positive multiple of 4 plus 2."
result = newSeqWith(n, newSeq[int](n))
 
let
halfN = n div 2
subSquareSize = n * n div 4
subSquare = magicSquareOdd(halfN)
 
const QuadrantFactors = [0, 2, 3, 1]
 
for r in 0..<n:
for c in 0..<n:
let quadrant = r div halfN * 2 + c div halfN
result[r][c] = subSquare[r mod halfN][c mod halfN] + QuadrantFactors[quadrant] * subSquareSize
 
let
nColsLeft = halfN div 2
nColsRight = nColsLeft - 1
 
for r in 0..<halfN:
for c in 0..<n:
if c < nColsLeft or c >= n - nColsRight or (c == nColsLeft and r == nColsLeft):
if c != 0 or r != nColsLeft:
swap result[r][c], result[r + halfN][c]
 
 
func `$`(square: Square): string =
## Return the string representation of a magic square.
let length = len($(square.len * square.len))
for row in square:
result.add row.mapIt(($it).align(length)).join(" ") & '\n'
 
 
when isMainModule:
let n = 6
echo magicSquareSinglyEven(n)
echo "Magic constant = ", n * (n * n + 1) div 2</syntaxhighlight>
 
{{out}}
<pre>35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
 
Magic constant = 111</pre>
 
=={{header|Perl}}==
 
See [[Magic_squares/Perl|Magic squares/Perl]] for a general magic square generator.
 
=={{header|Phix}}==
{{trans|FreeBASIC}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">swap</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y2</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y2</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y2</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">]}</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">se_magicsq</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">6</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"illegal size (%d)"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sq</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">magic_sum</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">sq_d_2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">q2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq_d_2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">x1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq_d_2</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y2</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #000080;font-style:italic;">-- fill pattern a c
-- d b
-- main loop for creating magic square in section a
-- the value for b,c and d is derived from a</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">x2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">sq_d_2</span>
<span style="color: #000000;">y2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">sq_d_2</span>
<span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span> <span style="color: #000080;font-style:italic;">-- a</span>
<span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">+</span><span style="color: #000000;">q2</span> <span style="color: #000080;font-style:italic;">-- b</span>
<span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">+</span><span style="color: #000000;">q2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span> <span style="color: #000080;font-style:italic;">-- c</span>
<span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">+</span><span style="color: #000000;">q2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">3</span> <span style="color: #000080;font-style:italic;">-- d</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sq_d_2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">x1</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">></span><span style="color: #000000;">sq_d_2</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">x1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;"><></span> <span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">x1</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sq_d_2</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;"><></span> <span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">></span><span style="color: #000000;">q2</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000080;font-style:italic;">-- swap left side</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">sq_d_2</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">y2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">sq_d_2</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">l</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">sq</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">swap</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- make indent</span>
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq_d_2</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #000000;">y2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">sq_d_2</span>
<span style="color: #000000;">x1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">sq</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">swap</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y2</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">x1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #000000;">sq</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">swap</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y2</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- swap right side</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">sq_d_2</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">y2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">sq_d_2</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">l</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">sq</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">swap</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- check columms and rows</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><></span><span style="color: #000000;">magic_sum</span>
<span style="color: #008080;">or</span> <span style="color: #000000;">l</span><span style="color: #0000FF;"><></span><span style="color: #000000;">magic_sum</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"error: value &lt;&gt; magic_sum"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- check diagonals</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">x2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x2</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><></span><span style="color: #000000;">magic_sum</span>
<span style="color: #008080;">or</span> <span style="color: #000000;">l</span><span style="color: #0000FF;"><></span><span style="color: #000000;">magic_sum</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"error: value &lt;&gt; magic_sum"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">sq</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">se_magicsq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">),{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_IntFmt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%3d"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_StrFmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_IntCh</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_Pause</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{{35, 3,31, 8,30, 4},
{ 1,32, 9,28, 5,36},
{ 6, 7, 2,33,34,29},
{26,21,22,17,12,13},
{19,23,27,10,14,18},
{24,25,20,15,16,11}}
</pre>
 
=={{header|Python}}==
{{trans|Lua}}
<syntaxhighlight lang="python">
import math
from sys import stdout
 
LOG_10 = 2.302585092994
 
 
# build odd magic square
def build_oms(s):
if s % 2 == 0:
s += 1
q = [[0 for j in range(s)] for i in range(s)]
p = 1
i = s // 2
j = 0
while p <= (s * s):
q[i][j] = p
ti = i + 1
if ti >= s: ti = 0
tj = j - 1
if tj < 0: tj = s - 1
if q[ti][tj] != 0:
ti = i
tj = j + 1
i = ti
j = tj
p = p + 1
 
return q, s
 
 
# build singly even magic square
def build_sems(s):
if s % 2 == 1:
s += 1
while s % 4 == 0:
s += 2
 
q = [[0 for j in range(s)] for i in range(s)]
z = s // 2
b = z * z
c = 2 * b
d = 3 * b
o = build_oms(z)
 
for j in range(0, z):
for i in range(0, z):
a = o[0][i][j]
q[i][j] = a
q[i + z][j + z] = a + b
q[i + z][j] = a + c
q[i][j + z] = a + d
 
lc = z // 2
rc = lc
for j in range(0, z):
for i in range(0, s):
if i < lc or i > s - rc or (i == lc and j == lc):
if not (i == 0 and j == lc):
t = q[i][j]
q[i][j] = q[i][j + z]
q[i][j + z] = t
 
return q, s
 
 
def format_sqr(s, l):
for i in range(0, l - len(s)):
s = "0" + s
return s + " "
 
 
def display(q):
s = q[1]
print(" - {0} x {1}\n".format(s, s))
k = 1 + math.floor(math.log(s * s) / LOG_10)
for j in range(0, s):
for i in range(0, s):
stdout.write(format_sqr("{0}".format(q[0][i][j]), k))
print()
print("Magic sum: {0}\n".format(s * ((s * s) + 1) // 2))
 
 
stdout.write("Singly Even Magic Square")
display(build_sems(6))
</syntaxhighlight>
{{out}}
<pre>Singly Even Magic Square - 6 x 6
 
35 01 06 26 19 24
03 32 07 21 23 25
31 09 02 22 27 20
08 28 33 17 10 15
30 05 34 12 14 16
04 36 29 13 18 11
Magic sum: 111</pre>
 
=={{header|R}}==
 
See [http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order#R here] for the solution for all three cases.
 
'''Example'''
 
<pre>> magic(6)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 35 1 6 26 19 24
[2,] 3 32 7 21 23 25
[3,] 31 9 2 22 27 20
[4,] 8 28 33 17 10 15
[5,] 30 5 34 12 14 16
[6,] 4 36 29 13 18 11</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
See [[Magic_squares/Raku|Magic squares/Raku]] for a general magic square generator.
{{out}}
With a parameter of 6:
Line 805 ⟶ 2,463:
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">def odd_magic_square(n)
n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} }
end
Line 844 ⟶ 2,502:
end
 
puts to_string(single_even_magic_square(6))</langsyntaxhighlight>
{{out}}
<pre>
Line 857 ⟶ 2,515:
===LUX method===
[[wp:Conway's LUX method for magic squares]]
<langsyntaxhighlight lang="ruby">class Magic_square
attr_reader :square
LUX = { L: [[4, 1], [2, 3]], U: [[1, 4], [2, 3]], X: [[1, 4], [3, 2]] }
Line 902 ⟶ 2,560:
end
 
sq = Magic_square.new(6).square</langsyntaxhighlight>
 
{{out}}
Line 912 ⟶ 2,570:
13 16 36 33 5 8
14 15 34 35 6 7
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::env;
 
fn main() {
let n: usize =
match env::args().nth(1).and_then(|arg| arg.parse().ok()).ok_or(
"Please specify the size of the magic square, as a positive multiple of 4 plus 2.",
) {
Ok(arg) if arg % 2 == 1 || arg >= 6 && (arg - 2) % 4 == 0 => arg,
Err(e) => panic!(e),
_ => panic!("Argument must be a positive multiple of 4 plus 2."),
};
 
let (ms, mc) = magic_square_singly_even(n);
println!("n: {}", n);
println!("Magic constant: {}\n", mc);
let width = (n * n).to_string().len() + 1;
for row in ms {
for elem in row {
print!("{e:>w$}", e = elem, w = width);
}
println!();
}
}
 
fn magic_square_singly_even(n: usize) -> (Vec<Vec<usize>>, usize) {
let size = n * n;
let half = n / 2;
let sub_square_size = size / 4;
let sub_square = magic_square_odd(half);
let quadrant_factors = [0, 2, 3, 1];
let cols_left = half / 2;
let cols_right = cols_left - 1;
 
let ms = (0..n)
.map(|r| {
(0..n)
.map(|c| {
let localr = if (c < cols_left
|| c >= n - cols_right
|| c == cols_left && r % half == cols_left)
&& !(c == 0 && r % half == cols_left)
{
if r >= half {
r - half
} else {
r + half
}
} else {
r
};
let quadrant = localr / half * 2 + c / half;
let v = sub_square[localr % half][c % half];
v + quadrant_factors[quadrant] * sub_square_size
})
.collect()
})
.collect::<Vec<Vec<_>>>();
(ms, (n * n + 1) * n / 2)
}
 
fn magic_square_odd(n: usize) -> Vec<Vec<usize>> {
(0..n)
.map(|r| {
(0..n)
.map(|c| {
n * (((c + 1) + (r + 1) - 1 + (n >> 1)) % n)
+ (((c + 1) + (2 * (r + 1)) - 2) % n)
+ 1
})
.collect::<Vec<_>>()
})
.collect::<Vec<Vec<_>>>()
}</syntaxhighlight>
{{out}}
<pre>
n: 6
Magic constant: 111
 
35 3 4 26 21 22
1 32 9 19 23 27
33 7 2 24 25 20
8 30 31 17 12 13
28 5 36 10 14 18
6 34 29 15 16 11
 
 
n: 10
Magic constant: 505
 
92 98 4 10 11 67 73 54 60 36
99 80 6 12 18 74 55 56 62 43
1 82 88 19 25 51 57 63 69 50
83 89 20 21 2 58 64 70 71 27
90 91 22 3 9 65 66 72 53 34
17 23 79 85 86 42 48 29 35 61
24 5 81 87 93 49 30 31 37 68
76 7 13 94 100 26 32 38 44 75
8 14 95 96 77 33 39 45 46 52
15 16 97 78 84 40 41 47 28 59
 
 
n: 18
Magic constant: 2925
 
290 300 310 320 6 16 26 36 37 209 219 229 239 168 178 107 117 118
301 311 321 250 17 27 28 38 48 220 230 240 169 179 189 109 119 129
312 322 251 261 19 29 39 49 59 231 241 170 180 181 191 120 130 140
323 252 253 263 30 40 50 60 70 242 171 172 182 192 202 131 141 151
1 254 264 274 284 51 61 71 81 163 173 183 193 203 213 142 152 162
255 265 275 285 52 62 72 73 2 174 184 194 204 214 224 153 154 83
266 276 286 296 63 64 74 3 13 185 195 205 215 225 226 155 84 94
277 287 297 298 65 75 4 14 24 196 206 216 217 227 237 85 95 105
288 289 299 309 76 5 15 25 35 207 208 218 228 238 167 96 106 116
47 57 67 77 249 259 269 279 280 128 138 148 158 87 97 188 198 199
58 68 78 7 260 270 271 281 291 139 149 159 88 98 108 190 200 210
69 79 8 18 262 272 282 292 302 150 160 89 99 100 110 201 211 221
80 9 10 20 273 283 293 303 313 161 90 91 101 111 121 212 222 232
244 11 21 31 41 294 304 314 324 82 92 102 112 122 132 223 233 243
12 22 32 42 295 305 315 316 245 93 103 113 123 133 143 234 235 164
23 33 43 53 306 307 317 246 256 104 114 124 134 144 145 236 165 175
34 44 54 55 308 318 247 257 267 115 125 135 136 146 156 166 176 186
45 46 56 66 319 248 258 268 278 126 127 137 147 157 86 177 187 197
</pre>
 
=={{header|Stata}}==
 
See [http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order#Stata here] for all three cases.
 
<pre>. mata magic(6)
1 2 3 4 5 6
+-------------------------------+
1 | 35 1 6 26 19 24 |
2 | 3 32 7 21 23 25 |
3 | 31 9 2 22 27 20 |
4 | 8 28 33 17 10 15 |
5 | 30 5 34 12 14 16 |
6 | 4 36 29 13 18 11 |
+-------------------------------+</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var magicSquareOdd = Fn.new { |n|
if (n < 3 || n%2 == 0) Fiber.abort("Base must be odd and > 2")
var value = 1
var gridSize = n * n
var c = (n/2).floor
var r = 0
var result = List.filled(n, null)
for (i in 0...n) result[i] = List.filled(n, 0)
while (value <= gridSize) {
result[r][c] = value
if (r == 0) {
if (c == n - 1) {
r = r + 1
} else {
r = n - 1
c = c + 1
}
} else if (c == n - 1) {
r = r - 1
c = 0
} else if (result[r - 1][c + 1] == 0) {
r = r - 1
c = c + 1
} else {
r = r + 1
}
value = value + 1
}
return result
}
 
var magicSquareSinglyEven = Fn.new { |n|
if (n < 6 || (n - 2) % 4 != 0) {
Fiber.abort("Base must be a positive multiple of 4 plus 2")
}
var size = n * n
var halfN = n / 2
var subSquareSize = size / 4
var subSquare = magicSquareOdd.call(halfN)
var quadrantFactors = [0, 2, 3, 1]
var result = List.filled(n, null)
for (i in 0...n) result[i] = List.filled(n, 0)
for (r in 0...n) {
for (c in 0...n) {
var quadrant = (r/halfN).floor * 2 + (c/halfN).floor
result[r][c] = subSquare[r % halfN][c % halfN]
result[r][c] = result[r][c] + quadrantFactors[quadrant] * subSquareSize
}
}
var nColsLeft = (halfN/2).floor
var nColsRight = nColsLeft - 1
for (r in 0...halfN) {
for (c in 0...n) {
if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) {
if (c != 0 || r != nColsLeft) {
var tmp = result[r][c]
result[r][c] = result[r + halfN][c]
result[r + halfN][c] = tmp
}
}
}
}
return result
}
 
var n = 6
for (ia in magicSquareSinglyEven.call(n)) {
for (i in ia) Fmt.write("$2d ", i)
System.print()
}
System.print("\nMagic constant %((n * n + 1) * n / 2)")</syntaxhighlight>
 
{{out}}
<pre>
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
 
Magic constant 111
</pre>
 
=={{header|zkl}}==
{{trans|Java}}
<langsyntaxhighlight lang="zkl">class MagicSquareSinglyEven{
fcn init(n){ var result=magicSquareSinglyEven(n) }
fcn toString{
Line 969 ⟶ 2,856:
result
}
}</langsyntaxhighlight>
<syntaxhighlight lang ="zkl">MagicSquareSinglyEven(6).println();</langsyntaxhighlight>
{{out}}
<pre>
338

edits