Magic squares of singly even order: Difference between revisions

Add C# implementation
(+Stata)
(Add C# implementation)
 
(23 intermediate revisions by 11 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.
 
<langsyntaxhighlight 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+,:^:</langsyntaxhighlight>
 
{{out}}
Line 35 ⟶ 523:
=={{header|C}}==
Takes number of rows from command line, prints out usage on incorrect invocation.
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<ctype.h>
Line 153 ⟶ 641:
return 0;
}
</syntaxhighlight>
</lang>
Invocation and Output:
<pre>
Line 165 ⟶ 653:
 
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 278 ⟶ 864:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 294 ⟶ 880:
=={{header|D}}==
{{trans|Java}}
<syntaxhighlight lang="d">
<lang d>
import std.exception;
import std.stdio;
Line 381 ⟶ 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 432 ⟶ 1,222:
end
 
Magic_square.singly_even(6)</langsyntaxhighlight>
 
{{out}}
Line 445 ⟶ 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 591 ⟶ 1,381:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Single even magic square size: 6*6
Line 605 ⟶ 1,395:
=={{header|Go}}==
{{trans|Java}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 706 ⟶ 1,496:
}
fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2)
}</langsyntaxhighlight>
 
{{out}}
Line 722 ⟶ 1,512:
=={{header|Haskell}}==
Using [[wp:Conway's LUX method for magic squares|Conway's LUX method for magic squares]]
<langsyntaxhighlight lang="haskell">import qualified Data.Map.Strict as M
import Data.List (transpose, intercalate)
import Data.Maybe (fromJust, isJust)
Line 827 ⟶ 1,617:
putStrLn $ unlines (table " " (fmap show <$> test))
print $ checked test
putStrLn ""</langsyntaxhighlight>
{{Out}}
<pre>32 29 4 1 24 21
Line 871 ⟶ 1,661:
Using the Strachey method:
 
<syntaxhighlight lang="j">
<lang J>
odd =: i:@<.@-: |."0 1&|:^:2 >:@i.@,~
t =: ((*: * i.@4:) +"0 2 odd)@-:
Line 883 ⟶ 1,673:
d =: ((lm * {.@t) + -.@lm * {:@t)
m =: (a ,"1 c) , d ,"1 b
</syntaxhighlight>
</lang>
 
{{Out}}
Line 915 ⟶ 1,705:
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 1,001 ⟶ 1,812:
return result;
}
}</langsyntaxhighlight>
 
<pre>35 1 6 26 19 24
Line 1,011 ⟶ 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}}
<langsyntaxhighlight lang="julia">function oddmagicsquare(order)
if iseven(order)
order += 1
Line 1,097 ⟶ 1,989:
check(msq)
end
</langsyntaxhighlight> {{output}}<pre>
With order 6:
35 30 31 8 3 4
Line 1,123 ⟶ 2,015:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun magicSquareOdd(n: Int): Array<IntArray> {
Line 1,192 ⟶ 2,084:
}
println("\nMagic constant ${(n * n + 1) * n / 2}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,210 ⟶ 2,102:
See [[Magic_squares/Lua]].
 
=={{header|PerlNim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import sequtils, strutils
 
type Square = seq[seq[int]]
See [[Magic_squares/Perl|Magic squares/Perl]] for a general magic square generator.
 
<lang perl></lang>
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>
 
=={{header|Perl 6}}==
See [[Magic_squares/Perl_6|Magic squares/Perl 6]] for a general magic square generator.
{{out}}
With a parameter of 6:
<pre>35 1 6 26 19 24
3 32 7 21 23 25
Line 1,226 ⟶ 2,187:
4 36 29 13 18 11
 
TheMagic magicconstant number is= 111</pre>
 
=={{header|Perl}}==
With a parameter of 10:
<pre> 92 99 1 8 15 67 74 51 58 40
98 80 7 14 16 73 55 57 64 41
4 81 88 20 22 54 56 63 70 47
85 87 19 21 3 60 62 69 71 28
86 93 25 2 9 61 68 75 52 34
17 24 76 83 90 42 49 26 33 65
23 5 82 89 91 48 30 32 39 66
79 6 13 95 97 29 31 38 45 72
10 12 94 96 78 35 37 44 46 53
11 18 100 77 84 36 43 50 27 59
 
See [[Magic_squares/Perl|Magic squares/Perl]] for a general magic square generator.
The magic number is 505</pre>
 
=={{header|Phix}}==
{{trans|FreeBASIC}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>procedure Abort(string msg)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
puts(1,msg&"\nPress any key...")
<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>
{} = wait_key()
<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>
abort(0)
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function swap(sequence s, integer x1, y1, x2, y2)
<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>
{s[x1,y1],s[x2,y2]} = {s[x2,y2],s[x1,y1]}
return s
<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>
end function
<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>
function se_magicsq(integer n)
<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>
if n<6 or mod(n-2,4)!=0 then
<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>
Abort(sprintf("illegal size (%d)",{n}))
<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>
end if
<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>
sequence sq = repeat(repeat(0,n),n)
<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>
integer magic_sum = n*(n*n+1)/2,
<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>
sq_d_2 = n/2,
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
q2 = power(sq_d_2,2),
l = (n-2)/4,
<span style="color: #000080;font-style:italic;">-- fill pattern a c
x1 = floor(sq_d_2/2)+1, x2,
-- y1 = 1, y2, d b
-- main loop for creating magic square rin =section 1a
-- 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>
-- fill pattern a c
<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>
-- d b
<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>
-- main loop for creating magic square in section a
<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>
-- the value for b,c and d is derived from a
<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>
while true do
<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>
if sq[x1,y1]=0 then
<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>
x2 = x1+sq_d_2
<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>
y2 = y1+sq_d_2
<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>
sq[x1,y1] = r -- a
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
sq[x2,y2] = r+q2 -- b
sq[x2,y1] <span style="color: r+q2*2 -- c#008080;">else</span>
<span style="color: #000000;">x1</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
sq[x1,y2] = r+q2*3 -- d
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
if mod(r,sq_d_2)=0 then
<span style="color: #008080;">end</span> y1<span +style="color: 1#008080;">if</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
else
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
x1 += 1
<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>
y1 -= 1
<span style="color: #000000;">x1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
end if
<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>
r += 1
<span style="color: #000000;">x1</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
if x1>sq_d_2 then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
x1 = 1
<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>
while sq[x1,y1] <> 0 do
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sq_d_2</span>
x1 += 1
<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>
end while
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
if y1<1 then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
y1 = sq_d_2
<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>
while sq[x1,y1] <> 0 do
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
y1 -= 1
end while
<span style="color: #000080;font-style:italic;">-- swap left side</span>
end if
<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>
if r>q2 then exit end if
<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>
end while
<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>
-- swap left side
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
for y1=1 to sq_d_2 do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
y2 = y1+sq_d_2
for x1=1 to l do
<span style="color: #000080;font-style:italic;">-- make indent</span>
sq = swap(sq, x1,y1, x1,y2)
<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>
end for
<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>
end for
<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>
-- make indent
<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>
y1 = floor(sq_d_2/2) +1
<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>
y2 = y1+sq_d_2
x1 = 1
<span style="color: #000080;font-style:italic;">-- swap right side</span>
sq = swap(sq, x1,y1, x1,y2)
<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>
x1 = l+1
<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>
sq = swap(sq, x1,y1, x1,y2)
<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>
-- swap right side
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
for y1=1 to sq_d_2 do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
y2 = y1+sq_d_2
for x1=n-l+2 to n do
<span style="color: #000080;font-style:italic;">-- check columms and rows</span>
sq = swap(sq, x1,y1, x1,y2)
<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>
end for
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
end for
<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>
-- check columms and rows
<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>
for y1=1 to n do
<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>
r = 0
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
l = 0
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><></span><span style="color: #000000;">magic_sum</span>
for x1=1 to n do
<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>
r += sq[x1,y1]
<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>
l += sq[y1,x1]
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if r<>magic_sum
or l<>magic_sum then
<span style="color: #000080;font-style:italic;">-- check diagonals</span>
Abort("error: value <> magic_sum")
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
end if
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
end for
<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>
-- check diagonals
<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>
r = 0
<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>
l = 0
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
for x1=1 to n do
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><></span><span style="color: #000000;">magic_sum</span>
r += sq[x1,x1]
<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>
x2 = n-x1+1
<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>
l += sq[x2,x2]
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
if r<>magic_sum
<span style="color: #008080;">return</span> <span style="color: #000000;">sq</span>
or l<>magic_sum then
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
Abort("error: value <> magic_sum")
end if
<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>-->
return sq
end function
pp(se_magicsq(6),{pp_Nest,1,pp_IntFmt,"%3d",pp_StrFmt,1,pp_Pause,0})</lang>
{{out}}
<pre>
Line 1,372 ⟶ 2,320:
=={{header|Python}}==
{{trans|Lua}}
<langsyntaxhighlight lang="python">
import math
from sys import stdout
Line 1,457 ⟶ 2,405:
stdout.write("Singly Even Magic Square")
display(build_sems(6))
</langsyntaxhighlight>
{{out}}
<pre>Singly Even Magic Square - 6 x 6
Line 1,483 ⟶ 2,431:
[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:
<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
 
The magic number is 111</pre>
 
With a parameter of 10:
<pre> 92 99 1 8 15 67 74 51 58 40
98 80 7 14 16 73 55 57 64 41
4 81 88 20 22 54 56 63 70 47
85 87 19 21 3 60 62 69 71 28
86 93 25 2 9 61 68 75 52 34
17 24 76 83 90 42 49 26 33 65
23 5 82 89 91 48 30 32 39 66
79 6 13 95 97 29 31 38 45 72
10 12 94 96 78 35 37 44 46 53
11 18 100 77 84 36 43 50 27 59
 
The magic number is 505</pre>
 
=={{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 1,525 ⟶ 2,502:
end
 
puts to_string(single_even_magic_square(6))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,538 ⟶ 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 1,583 ⟶ 2,560:
end
 
sq = Magic_square.new(6).square</langsyntaxhighlight>
 
{{out}}
Line 1,596 ⟶ 2,573:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::env;
 
fn main() {
Line 1,668 ⟶ 2,645:
})
.collect::<Vec<Vec<_>>>()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,734 ⟶ 2,711:
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 1,790 ⟶ 2,856:
result
}
}</langsyntaxhighlight>
<syntaxhighlight lang ="zkl">MagicSquareSinglyEven(6).println();</langsyntaxhighlight>
{{out}}
<pre>
337

edits