Magic squares of doubly even order: Difference between revisions

m
(Add Factor example)
imported>Arakov
 
(41 intermediate revisions by 21 users not shown)
Line 1:
{{task}}
A [[wp:Magic_square|magic square]] is an   '''NxNN×N'''  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   ''and''   both diagonals are equal to the same sum   (which is called the ''magic number'' or ''magic constant'').
 
A magic square of doubly even order has a size that is a multiple of four   (e.g.     '''4''', '''8''', '''12'''). This means that the subsquares also have an even size, which plays a role in the construction.
 
This means that the subsquares also have an even size, which plays a role in the construction.
 
<!-- As more computer programming languages will be added, they will "fill up" the space to the left of this light blue grid, and the first language entry will be the (normal) full width, so the big size is essential "free space". Gerard Schildberger. -->
Line 25 ⟶ 27:
<br>
;Task
Create a magic square of &nbsp; '''8 x&times; 8'''.
 
<br><br>
 
; Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of singly even order]]<br><br>
 
 
; See also:
;See also:
* [http://www.1728.org/magicsq2.htm Doubly Even Magic Squares (1728.org)]
<br><br>
 
=={{header|11l}}==
{{trans|Java}}
 
<syntaxhighlight lang="11l">F magicSquareDoublyEven(n)
V bits = 1001'0110'0110'1001b
V size = n * n
V mult = n I/ 4
 
V result = [[0] * n] * n
V i = 0
L(r) 0 .< n
L(c) 0 .< n
V bitPos = c I/ mult + (r I/ mult) * 4
result[r][c] = I (bits [&] (1 << bitPos)) != 0 {i + 1} E size - i
i++
R result
 
V n = 8
L(row) magicSquareDoublyEven(n)
L(x) row
print(‘#2 ’.format(x), end' ‘’)
print()
print("\nMagic constant: "((n * n + 1) * n I/ 2))</syntaxhighlight>
 
{{out}}
<pre>
1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
Magic constant: 260
</pre>
 
=={{header|360 Assembly}}==
{{trans|Java}}
<langsyntaxhighlight lang="360asm">* Magic squares of doubly even order 01/03/2017
MAGICSDB CSECT
USING MAGICSDB,R13
Line 100 ⟶ 141:
XDEC DS CL12 temp for xdeco
YREGS
END MAGICSDB</langsyntaxhighlight>
{{out}}
<pre>
Line 112 ⟶ 153:
57 58 6 5 4 3 63 64
magic constant= 260
</pre>
 
=={{header|ALGOL 60}}==
{{works with|A60}}
<syntaxhighlight lang="algol60">begin
comment Magic squares of doubly even order - 10/02/2021;
integer array pattern[1:4,1:4];
integer n, r, c, s, m, i, b, t;
n:=8;
for r:=1 step 1 until 4 do
for c:=1 step 1 until 4 do
pattern[r,c]:=if
((c=1 or c=4) and (r=1 or r=4)) or
((c=2 or c=3) and (r=2 or r=3)) then 1 else 0;
s:=n*n; m:=n div 4;
outstring(1,"magic square -- n ="); outinteger(1,n); outstring(1,"\n");
i:=0;
for r:=1 step 1 until n do begin
for c:=1 step 1 until n do begin
b:=pattern[(r-1) div m+1,(c-1) div m+1];
if b=1 then t:=i+1 else t:=s-i;
if t less 10 then outstring(1," ");
outinteger(1,t);
i:=i+1
end;
outstring(1,"\n")
end;
outstring(1,"magic constant ="); outinteger(1,(s+1)*n div 2)
end </syntaxhighlight>
{{out}}
<pre>
magic square -- n = 8
1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
magic constant = 260
</pre>
 
=={{header|ALGOL 68}}==
{{Trans|ALGOL 60}}
Using a procedure to generate the square for easier re-use.
<syntaxhighlight lang="algol68">BEGIN # Magic squares of doubly even order #
PROC doubly even magic square = ( INT n )[,]INT:
IF n MOD 4 /= 0 THEN
# not a doubly even number #
[ 1 : 0, 1 : 0 ]INT empty square;
empty square
ELSE
# ok to create the square #
[ 1 : 4, 1 : 4 ]INT pattern;
FOR r TO 4 DO
FOR c TO 4 DO
pattern[ r, c ] := IF ( ( c = 1 OR c = 4 ) AND ( r = 1 OR r = 4 ) )
OR ( ( c = 2 OR c = 3 ) AND ( r = 2 OR r = 3 ) )
THEN 1
ELSE 0
FI
OD
OD;
[ 1 : n, 1 : n ]INT result;
INT s = n * n, m = n OVER 4;
INT i := 0;
FOR r TO n DO
FOR c TO n DO
result[ r, c ] := IF pattern[ ( r - 1 ) OVER m + 1, ( c - 1 ) OVER m + 1 ] = 1
THEN i + 1
ELSE s - i
FI;
i +:= 1
OD
OD;
result
FI # doubly eben magic square # ;
# test doubly even magic square #
FOR order FROM 8 BY 4 TO 12 DO
# calculate the field width for the elements of the square #
INT w := 1, v := order * order;
WHILE ( v OVERAB 10 ) > 0 DO w +:= 1 OD;
# construct the square #
[,]INT square = doubly even magic square( order );
print( ( "magic square -- n = ", whole( order, 0 ), newline ) );
FOR r FROM 1 LWB square TO 1 UPB square DO
FOR c FROM 2 LWB square TO 2 UPB square DO
print( ( " ", whole( square[ r, c ], - w ) ) )
OD;
print( ( newline ) )
OD;
print( ( "magic constant = ", whole( ( ( ( order * order ) + 1 ) * order ) OVER 2, 0 ), newline ) )
OD
END</syntaxhighlight>
{{out}}
<pre>
magic square -- n = 8
1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
magic constant = 260
magic square -- n = 12
1 2 3 141 140 139 138 137 136 10 11 12
13 14 15 129 128 127 126 125 124 22 23 24
25 26 27 117 116 115 114 113 112 34 35 36
108 107 106 40 41 42 43 44 45 99 98 97
96 95 94 52 53 54 55 56 57 87 86 85
84 83 82 64 65 66 67 68 69 75 74 73
72 71 70 76 77 78 79 80 81 63 62 61
60 59 58 88 89 90 91 92 93 51 50 49
48 47 46 100 101 102 103 104 105 39 38 37
109 110 111 33 32 31 30 29 28 118 119 120
121 122 123 21 20 19 18 17 16 130 131 132
133 134 135 9 8 7 6 5 4 142 143 144
magic constant = 870
</pre>
 
=={{header|Amazing Hopper}}==
{{Trans|C++}}
<syntaxhighlight lang="c">
/*
Magic squares of doubly even order. Rosettacode.org
By Mr. Dalien.
*/
 
#include <basico.h>
 
#proto cuadradomágico(_X_)
#synon _cuadradomágico generarcuadradomágico
 
principal {
decimales '0', fijar separador 'NULO'
malla de bits(bits,'1;0;0;1','0;1;1;0','0;1;1;0','1;0;0;1')
borrar pantalla
iterar para( i=1; n=4, #(i<=3), ++i; #(n=4*i) )
dim( #(n*n) ) matriz de ceros 'sqr'
generar cuadrado mágico (n);
ir a sub ( meter en tabla, sqr, #(n+1) ), para 'sqr'
imprimir '"Magic square order ",n,\
"\nMagic constant : ",#((n * n + 1) * n / 2),\
NL,sqr,NL,NL'
luego limpiar 'sqr'
siguiente
terminar
}
 
subrutinas
 
sub( meter en tabla, s, n ) {
i=n,rareti(i, 'i')
retener 'n', insertar columnas en 's'
insertar filas en 's'
#basic{
s[1:2:2*n-1,1:_end_] = "---"
s[1:_end_, 1:2:2*n-1] = "|"
s[1:2:_end_,1:2:_end_] = "+"
}
retornar 's'
}
 
cuadrado mágico ( n )
iterar para ( cr=0;i=0, #(cr<n), ++cr )
iterar para ( cc=0, #(cc<n), ++cc;++i )
#( sqr[ (cc+n*cr)+1 ] = (bits[(cr%4+1),(cc%4+1)]) ? (i+1) : (n^2-i); )
siguiente
siguiente
#( sqr = lpad(" ",3,string(sqr)))
redim ( sqr, n, n )
retornar
</syntaxhighlight>
{{out}}
<pre>
Magic square order 4
Magic constant : 34
+---+---+---+---+
| 1| 15| 14| 4|
+---+---+---+---+
| 12| 6| 7| 9|
+---+---+---+---+
| 8| 10| 11| 5|
+---+---+---+---+
| 13| 3| 2| 16|
+---+---+---+---+
 
 
Magic square order 8
Magic constant : 260
+---+---+---+---+---+---+---+---+
| 1| 63| 62| 4| 5| 59| 58| 8|
+---+---+---+---+---+---+---+---+
| 56| 10| 11| 53| 52| 14| 15| 49|
+---+---+---+---+---+---+---+---+
| 48| 18| 19| 45| 44| 22| 23| 41|
+---+---+---+---+---+---+---+---+
| 25| 39| 38| 28| 29| 35| 34| 32|
+---+---+---+---+---+---+---+---+
| 33| 31| 30| 36| 37| 27| 26| 40|
+---+---+---+---+---+---+---+---+
| 24| 42| 43| 21| 20| 46| 47| 17|
+---+---+---+---+---+---+---+---+
| 16| 50| 51| 13| 12| 54| 55| 9|
+---+---+---+---+---+---+---+---+
| 57| 7| 6| 60| 61| 3| 2| 64|
+---+---+---+---+---+---+---+---+
 
 
Magic square order 12
Magic constant : 870
+---+---+---+---+---+---+---+---+---+---+---+---+
| 1|143|142| 4| 5|139|138| 8| 9|135|134| 12|
+---+---+---+---+---+---+---+---+---+---+---+---+
|132| 14| 15|129|128| 18| 19|125|124| 22| 23|121|
+---+---+---+---+---+---+---+---+---+---+---+---+
|120| 26| 27|117|116| 30| 31|113|112| 34| 35|109|
+---+---+---+---+---+---+---+---+---+---+---+---+
| 37|107|106| 40| 41|103|102| 44| 45| 99| 98| 48|
+---+---+---+---+---+---+---+---+---+---+---+---+
| 49| 95| 94| 52| 53| 91| 90| 56| 57| 87| 86| 60|
+---+---+---+---+---+---+---+---+---+---+---+---+
| 84| 62| 63| 81| 80| 66| 67| 77| 76| 70| 71| 73|
+---+---+---+---+---+---+---+---+---+---+---+---+
| 72| 74| 75| 69| 68| 78| 79| 65| 64| 82| 83| 61|
+---+---+---+---+---+---+---+---+---+---+---+---+
| 85| 59| 58| 88| 89| 55| 54| 92| 93| 51| 50| 96|
+---+---+---+---+---+---+---+---+---+---+---+---+
| 97| 47| 46|100|101| 43| 42|104|105| 39| 38|108|
+---+---+---+---+---+---+---+---+---+---+---+---+
| 36|110|111| 33| 32|114|115| 29| 28|118|119| 25|
+---+---+---+---+---+---+---+---+---+---+---+---+
| 24|122|123| 21| 20|126|127| 17| 16|130|131| 13|
+---+---+---+---+---+---+---+---+---+---+---+---+
|133| 11| 10|136|137| 7| 6|140|141| 3| 2|144|
+---+---+---+---+---+---+---+---+---+---+---+---+
 
</pre>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">-- MAGIC SQUARE OF DOUBLY EVEN ORDER -----------------------------------------
 
-- magicSquare :: Int -> [[Int]]
Line 369 ⟶ 652:
end tell
return v
end |until|</langsyntaxhighlight>
{{Out}}
magic(8)
Line 391 ⟶ 674:
| 8 || 58 || 59 || 5 || 61 || 3 || 2 || 64
|}
 
=={{header|AWK}}==
{{trans|C#}}
Since standard awk does not support bitwise operators, we provide the function countup to do the magic.
<syntaxhighlight lang="awk"># Usage: GAWK -f MAGIC_SQUARES_OF_DOUBLY_EVEN_ORDER.AWK
BEGIN {
n = 8
msquare[0, 0] = 0
if (magicsquaredoublyeven(msquare, n)) {
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%2d ", msquare[i, j])
}
printf("\n")
}
printf("\nMagic constant: %d\n", (n * n + 1) * n / 2)
exit 1
} else {
exit 0
}
}
function magicsquaredoublyeven(msquare, n, size, mult, r, c, i) {
if (n < 4 || n % 4 != 0) {
printf("Base must be a positive multiple of 4.\n")
return 0
}
size = n * n
mult = n / 4 # how many multiples of 4
 
i = 0
for (r = 0; r < n; r++) {
for (c = 0; c < n; c++) {
msquare[r, c] = countup(r, c, mult) ? i + 1 : size - i
i++
}
}
return 1
}
function countup(r, c, mult, pattern, bitpos) {
# Returns 1, if we are in a count-up zone (0 otherwise)
pattern = "1001011001101001"
bitpos = int(c / mult) + int(r / mult) * 4 + 1
return substr(pattern, bitpos, 1) + 0
}</syntaxhighlight>
 
{{out}}
<pre> 1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
Magic constant: 260</pre>
 
=={{header|Befunge}}==
The size, ''N'', is specified by the first value on the stack. The algorithm is loosely based on the [[Magic_squares_of_doubly_even_order#Java|Java]] implementation.
 
<langsyntaxhighlight lang="befunge">8>>>v>10p00g:*1-*\110g2*-*+1+.:00g%!9+,:#v_@
p00:<^:!!-!%3//4g00%g00\!!%3/*:g00*4:::-1<*:</langsyntaxhighlight>
 
{{out}}
Line 410 ⟶ 749:
=={{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 473 ⟶ 812:
return 0;
}
</syntaxhighlight>
</lang>
Invocation and Output :
<pre>
Line 492 ⟶ 831:
133 134 135 9 8 7 6 5 4 142 143 144
</pre>
 
=={{header|C sharp|C#}}==
{{trans|Java}}
<syntaxhighlight lang="csharp">using System;
 
namespace MagicSquareDoublyEven
{
class Program
{
static void Main(string[] args)
{
int n = 8;
var result = MagicSquareDoublyEven(n);
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
Console.Write("{0,2} ", result[i, j]);
Console.WriteLine();
}
Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2);
Console.ReadLine();
}
 
private static int[,] MagicSquareDoublyEven(int n)
{
if (n < 4 || n % 4 != 0)
throw new ArgumentException("base must be a positive "
+ "multiple of 4");
 
// pattern of count-up vs count-down zones
int bits = 0b1001_0110_0110_1001;
int size = n * n;
int mult = n / 4; // how many multiples of 4
 
int[,] result = new int[n, n];
 
for (int r = 0, i = 0; r < n; r++)
{
for (int c = 0; c < n; c++, i++)
{
int bitPos = c / mult + (r / mult) * 4;
result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
}
}</syntaxhighlight>
<pre> 1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
Magic constant: 260</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
#include <iomanip>
Line 546 ⟶ 943:
s.display();
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 561 ⟶ 958:
57 7 6 60 61 3 2 64
</pre>
 
=={{header|C#}}==
{{trans|Java}}
<lang csharp>using System;
 
namespace MagicSquareDoublyEven
{
class Program
{
static void Main(string[] args)
{
int n = 8;
var result = MagicSquareDoublyEven(n);
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
Console.Write("{0,2} ", result[i, j]);
Console.WriteLine();
}
Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2);
Console.ReadLine();
}
 
private static int[,] MagicSquareDoublyEven(int n)
{
if (n < 4 || n % 4 != 0)
throw new ArgumentException("base must be a positive "
+ "multiple of 4");
 
// pattern of count-up vs count-down zones
int bits = 0b1001_0110_0110_1001;
int size = n * n;
int mult = n / 4; // how many multiples of 4
 
int[,] result = new int[n, n];
 
for (int r = 0, i = 0; r < n; r++)
{
for (int c = 0; c < n; c++, i++)
{
int bitPos = c / mult + (r / mult) * 4;
result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
}
}</lang>
<pre> 1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
Magic constant: 260</pre>
 
=={{header|D}}==
{{trans|Java}}
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 657 ⟶ 996:
 
return result;
}</langsyntaxhighlight>
 
{{out}}
Line 670 ⟶ 1,009:
 
Magic constant: 260</pre>
 
=={{header|EDSAC order code}}==
<syntaxhighlight lang="edsac">
[Magic squares of doubly even order, for Rosetta Code.
EDSAC program, Initial Orders 2.]
[====================================================================================
Certain cells in the square are marked, such that if a cell is marked then so is
its reflection in the centre point of the square. Cells are numbered 1, 2, 3 ...
from left to right and top to bottom, but if a cell is marked it is swapped with its
reflection. Two marking methods are used, illustrated below for an 8x8 square.
+ o o + + o o + + + o o o o + +
o + + o o + + o + + o o o o + +
o + + o o + + o o o + + + + o o
+ o o + + o o + o o + + + + o o o = unmarked
+ o o + + o o + o o + + + + o o + = marked
o + + o o + + o o o + + + + o o
o + + o o + + o + + o o o o + +
+ o o + + o o + + + o o o o + +
Diagonal method Rectangle method
====================================================================================]
[Arrange the storage]
T45K P56F [H parameter: subroutine to print string]
T46K P100F [N parameter: subroutine to print number]
T47K P204F [M parameter: main routine]
T54K P200F [C parameter: constants read by subroutine R2]
 
[Library subroutine R2: reads integers from tape and can then be overwritten.]
GK T20F VD L8F A40D UD TF I40F A40F S39F G@ S2F G23F A5@ T5@ E4@ E13Z
T#C [tell R2 where to store values]
13743895347F8589934592#TZ
[C parameter: masks read in by subroutine R2, not by the regular loader]
[0] PF PF [diagonal method, binary 01100110011001100110011001100110011]
[2] PF PF [rectangle method, binary 01000000000000000000000000000000000]
 
[M parameter Main routine + high-level subroutine]
E25K TM GK
[35-bit values, must be at even address]
[0] PF PF [initial value of x mask]
[2] PF [x-mask, low 17 bits]
[3] PF [x-mask, high 17 bits]
[4] PF [y-mask, low 17 bits]
[5] PF [y-mask, high 17 bits]
[17-bit values]
[6] PF [sign bit from y mask]
[7] PF [m, input by user]
[8] PF [n = 4*m = order of magic square]
[9] PF [n^2 + 1]
[10] PF [negative counter for x-values (columns)]
[11] PF [negative counter for y-values (rows)]
[12] PF [current entry 1, 2, 3, ...]
[13] PD [constant 1]
[14] K4096F [null]
[15] !F [space]
[16] @F [carriage return]
[17] &F [line feed]
[18] P10F [to check for user dialling '0']
[Strings to be printed]
[19] K2048FMFAFGFIFCF!FSFQFUFAFRFEF!FOFFF!FOFRFDFEFRF!F#FRF*FMF@F&FK4096F
[49] K2048FDFIFAFLF!FMF!F#FKFPF!F*FTFOF!FCFAFNFCFEFLF#FLF!FK4096F
[75] K2048FDFIFAFGFOFNFAFLF!FMFEFTFHFOFDF#FCF@F&FK4096F
[96] K2048FRFEFCFTFAFNFGFLFEF!FMFEFTFHFOFDF#FCF@F&FK4096F
 
[Enter with acc = 0]
[118] A118@ GH A19@ [print 'MAGIC SQUARE OF ORDER 4M']
[121] A121@ GH A49@ [print 'DIAL M (0 TO CANCEL)']
ZF [halt machine; restarts when user dials a number]
[Here acc holds number of pulses in address field]
S18@ E175@ [exit if dialled '0' (10 pulses)]
A18@ [restore acc after test; m is in address field]
L512F [shift 11 left for printing]
UF [temp to 0F]
OF O16@ O17@ [print m followed by CR, LF]
R1024F [shift 12 right, m is now right-justified]
U7@ [store m]
L1F T8@ [shift 2 left and store n = 4*m]
H8@ V8@ [acc := n^2]
L64F L64F [shift 16 left to adjust scaling after mult]
A13@ T9@ [store n^2 + 1 = sum of a cell and its reflection]
[143] A143@ GH A75@ [print 'DIAGONAL METHOD:']
A#C [acc := diagonal mask]
U#@ [store as x-mask at start of each row]
T4#@ [also as initial value of y-mask]
[149] A149@ G177@ [call subroutine to print magic square]
[151] A151@ GH A96@ [print 'RECTANGLE METHOD:']
A2#C U4D T6D [copy rectangke mask to 4D and 6D]
S7@ [initialize negative counter to -m]
[158] TF [loop: update negative counter in 0F]
A4D RD T4D [shift 4D 1 right]
A6D R2F T6D [shift 6D 3 right]
AF A13@ [inc negative counter]
G158@ [loop back till done m times]
A4D S6D L1F [acc := 4D - 6D, then 2 left]
[Mask in binary is now 0 (m times) 1 (2*m times) 0...0]
U#@ [store as x-mask at start of each row]
T4#@ [also as initial value of y-mask]
[173] A173@ G177@ [call subroutine to print magic square]
[175] O14@ [done; print null to flush teleprinter buffer]
ZF [halt machine]
 
[Subroutine to print magic square after x- and y-mask have been initialized.]
[It's assumed that strings printed by caller leave teleprinter in figures mode.]
[177] A3F T220@ [plant return link as usual]
A15@ T1F [space replaces leading 0 when printing]
T12@ [initialize cell entry to 0]
S8@ [initialize negative counter of rows to -n]
[Start of row]
[183] T11@ [update negative counter of rows]
A#@ T2#@ [reset x-mask for start of row]
H14@ C5@ T6@ [isolate sign bit of y-mask]
S8@ [initialize negative counter of columns to -n]
[Next cell in this row.
Cell is considered marked if sign bits in x- and y-masks are equal.
Or could say marked if sign bits are unequal; would also give a magic square.]
[190] T10@ [update negative counter of columns]
A12@ A13@ T12@ [inc cell entry]
A3@ A6@ [compare signs in x- and y-masks]
E200@ [jump if equal (or could replace E by G)]
TF [clear acc]
A12@ [acc := entry]
E203@ [join common code]
[200] TF [clear acc]
A9@ S12@ [acc := complement of entry]
[203] TF [to 0F for printing]
[204] A204@ GN [print number]
A2#@ LD T2#@ [shift x-mask 1 left]
A10@ A13@ [inc negative counter of cells]
G190@ [loop till row is complete]
[End of row]
O16@ O17@ [print CR, LF]
A4#@ LD T4#@ [shift y-mask 1 left]
A11@ A13@ [inc negative counter of rows]
G183@ [loop till magic square is complete]
[220] ZF [(planted) jump back to caller]
 
[H parameter: Subroutine to print a string.]
E25K TH
[Input: A order for first character must follow subroutine call (G order)
String is terminated with EDSAC null, which is sent to the teleprinter.]
GKA18@U17@S19@T4@AFT6@AFUFOFE12@A20@G16@TFA6@A2FG5@TFZFU3FU1FK2048F
 
[N parameter: Subroutine to print non-negative 17-bit integer.]
E25K TN
[Parameters: 0F = integer to be printed (not preserved)
1F = character for leading zero (preserved)
Workspace: 4F..7F, 38 locations]
GKA3FT34@A1FT7FS35@T6FT4#FAFT4FH36@V4FRDA4#FR1024FH37@E23@O7FA2F
T6FT5FV4#FYFL8FT4#FA5FL1024FUFA6FG16@OFTFT7FA6FG17@ZFP4FZ219DTF
 
[M parameter again]
E25K TM GK
E118Z [define entry point]
PF [acc = 0 on entry]
 
</syntaxhighlight>
{{out}}
<pre>
MAGIC SQUARE OF ORDER 4M
DIAL M (0 TO CANCEL) 2
DIAGONAL METHOD:
64 2 3 61 60 6 7 57
9 55 54 12 13 51 50 16
17 47 46 20 21 43 42 24
40 26 27 37 36 30 31 33
32 34 35 29 28 38 39 25
41 23 22 44 45 19 18 48
49 15 14 52 53 11 10 56
8 58 59 5 4 62 63 1
RECTANGLE METHOD:
64 63 3 4 5 6 58 57
56 55 11 12 13 14 50 49
17 18 46 45 44 43 23 24
25 26 38 37 36 35 31 32
33 34 30 29 28 27 39 40
41 42 22 21 20 19 47 48
16 15 51 52 53 54 10 9
8 7 59 60 61 62 2 1
</pre>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions'routines;
Line 680 ⟶ 1,197:
{
if(n < 4 || n.mod(4) != 0)
{ InvalidArgumentException.new:("base must be a positive multiple of 4").raise() };
int bits := 09669h;
Line 686 ⟶ 1,203:
int mult := n / 4;
var result := new IntMatrix.allocate(n,n);
int i := 0;
for (int r := 0,; r < n,; r += 1)
{
for(int c := 0,; c < n,; c += 1,; i += 1)
{
int bitPos := c / mult + (r / mult) * 4;
result[r][c] := ((bits && (1 $shl bitPos)) != 0).iif(i+1,size - i)
}
};
Line 708 ⟶ 1,225:
console.printLine().printLine("Magic constant: ",(n * n + 1) * n / 2)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 724 ⟶ 1,241:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Magic_square do
def doubly_even(n) when rem(n,4)!=0, do: raise ArgumentError, "must be even, but not divisible by 4."
def doubly_even(n) do
Line 750 ⟶ 1,267:
end
 
Magic_square.doubly_even(8)</langsyntaxhighlight>
 
{{out}}
Line 765 ⟶ 1,282:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: arrays combinators.short-circuit formatting fry
generalizations kernel math math.matrices prettyprint sequences
;
Line 812 ⟶ 1,329:
] each ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 850 ⟶ 1,367:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 18-03-2016
' compile with: fbc -s console
' doubly even magic square 4, 8, 12, 16...
Line 969 ⟶ 1,486:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Single even magic square size: 8*8
Line 984 ⟶ 1,501:
 
=={{header|Go}}==
<langsyntaxhighlight Golang="go">package main
 
import (
Line 1,035 ⟶ 1,552:
fmt.Printf("\nMagic Constant: %d\n", magicConstant)
}
</syntaxhighlight>
</lang>
{{Out}}
<pre> 1 2 62 61 60 59 7 8
Line 1,050 ⟶ 1,567:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.List (transpose, unfoldr, intercalate)
import Data.List.Split (chunksOf)
import Data.Bool (bool)
import Control.Monad (forM_)
 
Line 1,058 ⟶ 1,576:
| rem n 4 > 0 = []
| otherwise =
chunksOf n $ zipWith (flip (bool =<< (-) limit)) series [1 .. sqr]
zipWith
(\x i ->
if x
then i
else limit - i)
series
[1 .. sqr]
where
sqr = n * n
Line 1,081 ⟶ 1,592:
isPowerOf :: Int -> Int -> Bool
isPowerOf k n = until ((0 /=) . flip rem k) (`quot` k) n == 1
 
 
-- TEST AND DISPLAY FUNCTIONS --------------------------------------------------
 
checked :: [[Int]] -> (Int, Bool)
checked square =
Line 1,110 ⟶ 1,619:
putStrLn $ unlines (table " " (fmap show <$> test))
print $ checked test
putStrLn ""[]</langsyntaxhighlight>
{{Out}}
<pre>main 1 15 14 4
1 15 14 4
12 6 7 9
8 10 11 5
Line 1,151 ⟶ 1,659:
 
=={{header|J}}==
<syntaxhighlight lang="j">
<lang J>
mask masksq=: >:@#@,#: 8| $_1&^ 153* 1021 102+ 153i.@$
t pat4=: ,:(, 65&-+.|.) each >:=i.644
mask=: ,/@(,./"3@$&pat4)@] ,~ % 4:
8 8 $ mask{each t
demsq=: masksq@mask
</lang>
</syntaxhighlight>
{{Out}}
{{out}}
<pre>
demsq 8
┌──┬──┬──┬──┬──┬──┬──┬──┐
64 2 3 61 60 6 7 57
│64│2 │3 │61│60│6 │7 │57│
9 55 54 12 13 51 50 16
├──┼──┼──┼──┼──┼──┼──┼──┤
17 47 46 20 21 43 42 24
│9 │55│54│12│13│51│50│16│
40 26 27 37 36 30 31 33
├──┼──┼──┼──┼──┼──┼──┼──┤
32 34 35 29 28 38 39 25
│17│47│46│20│21│43│42│24│
41 23 22 44 45 19 18 48
├──┼──┼──┼──┼──┼──┼──┼──┤
49 15 14 52 53 11 10 56
│40│26│27│37│36│30│31│33│
8 58 59 5 4 62 63 1
├──┼──┼──┼──┼──┼──┼──┼──┤
~.(+/,&,+/"1)demsq 128
│32│34│35│29│28│38│39│25│
1048640
├──┼──┼──┼──┼──┼──┼──┼──┤
│41│23│22│44│45│19│18│48│
├──┼──┼──┼──┼──┼──┼──┼──┤
│49│15│14│52│53│11│10│56│
├──┼──┼──┼──┼──┼──┼──┼──┤
│8 │58│59│5 │4 │62│63│1 │
└──┴──┴──┴──┴──┴──┴──┴──┘
</pre>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class MagicSquareDoublyEven {
 
public static void main(String[] args) {
Line 1,210 ⟶ 1,713:
return result;
}
}</langsyntaxhighlight>
 
<pre> 1 2 62 61 60 59 7 8
Line 1,222 ⟶ 1,725:
 
Magic constant: 260</pre>
 
 
=={{header|JavaScript}}==
Line 1,228 ⟶ 1,730:
===ES6===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
// doubleEvenMagicSquaredoublyEvenMagicSquare :: Int -> [[Int]]
const doubleEvenMagicSquaredoublyEvenMagicSquare = n => {
if0 === (n % 4 >? 0(() return=> undefined;{
const
sqr = n * n,
power = Math.log2(sqr),
scale = replicate(n / 4);
return chunksOf(n)(
map((x, i) => x ? 1 + i : sqr - i)(
isInt(power) ? truthSeries(power) : (
compose(
flatten,
scale,
map(scale),
chunksOf(4)
)(truthSeries(4))
)
)
);
})() : undefined;
 
// truthSeries :: Int -> [IntBool]
const truthSeries = n => {
0 >= n if? (n <= 0) return [true];
[true]
) : (() => {
const xs = truthSeries(n - 1);
return xs.concat(xs.map(x => !x));
})();
 
const sqr = n * n,
scale = curry(replicate)(n / 4),
power = Math.log2(sqr),
sequence = isInt(power) ? truthSeries(power) : (
flatten(
scale(
splitEvery(4, truthSeries(4))
.map(scale)
)
)
);
 
return splitEvery(n, sequence
.map((x, i) => x ? i + 1 : sqr - i));
};
 
// TEST -----------------------------------------------
const main = () =>
// Magic squares of orders 4, 8 and 12, with
// checks of row, column and diagonal sums.
intercalate('\n\n')(
map(n => {
const
lines = doublyEvenMagicSquare(n),
sums = map(sum)(
lines.concat(
transpose(lines)
.concat(diagonals(lines))
)
),
total = sums[0];
return unlines([
"Order: " + str(n),
"Summing to: " + str(total),
"Row, column and diagonal sums checked: " +
str(all(eq(total))(sums)) + '\n',
unlines(map(compose(
intercalate(' '),
map(compose(justifyRight(3)(' '), str))
))(lines))
]);
})([4, 8, 12])
);
 
// GENERIC FUNCTIONS ----------------------------------------------------
 
// GENERIC FUNCTIONS ----------------------------------
// flatten :: Tree a -> [a]
const flatten = t => (t instanceof Array ? concatMap(flatten, t) : [t]);
 
// concatMapall :: (a -> [b]Bool) -> [a] -> [b]Bool
const concatMapall = (f, xs)p => [].concat.apply([], xs.map(f));
// True if p(x) holds for every x in xs.
xs => xs.every(p);
 
// splitEverychunksOf :: Int -> [a] -> [][a]]
const splitEverychunksOf = (n, => xs) => {
if enumFromThenTo(0)(xs.length <= n) return [xs];(
const [h, t] = [xs.slice(0,length n),- xs.slice(n)];1
return [h]).concatreduce(splitEvery(n, t));
(a, i) => a.concat([xs.slice(i, (n + i))]),
}
[]
);
 
// currycompose (<<<) :: ((a, b) -> c) -> (a -> b) -> a -> c
const currycompose = f(...fs) => a => b => f(a, b);
x => fs.reduceRight((a, f) => f(a), x);
 
// replicatediagonals :: Int[[a]] -> [[a ->], [a]]
const replicatediagonals = (n, a)rows => {
let// vTwo =diagonal [a]sequences,
// from top left oand =bottom [];left
if// (nrespectively, <of 1)a returngiven o;matrix.
while map(n > 1flip(zipWith(index) {)(
if enumFromTo(n & 10) o = o.concat(v);pred(
n >>= 1; 0 < rows.length ? (
v = v rows[0].concat(v);length
} ) : 0
return o.concat(v ));
))([rows, reverse(rows)]);
 
// enumFromThenTo :: Int -> Int -> Int -> [Int]
const enumFromThenTo = x1 => x2 => y => {
const d = x2 - x1;
return Array.from({
length: Math.floor(y - x2) / d + 2
}, (_, i) => x1 + (d * i));
};
 
// isIntenumFromTo :: Int -> BoolInt -> [Int]
const isIntenumFromTo = xm => xn === Math.floor(x);>
Array.from({
length: 1 + n - m
}, (_, i) => m + i);
 
// eq (==) :: Eq a => a -> a -> Bool
const eq = a => b => a === b;
 
// flatten :: NestedList a -> [a]
// TEST AND DISPLAY FUNCTIONS -------------------------------------------
const flatten = nest => nest.flat(Infinity);
 
// transposeflip :: [[(a]] -> [[b -> c) -> b -> a]] -> c
const transposeflip = xsf =>
xs[0].map((_, iCol)x => xs.map((row)y => row[iCol]f(y)(x);
 
// diagonalsindex (!!) :: [[a]] -> ([a],Int -> [a])
const diagonalsindex = xs => {i => xs[i];
const nRows = xs.length,
nCols = (nRows > 0 ? xs[0].length : 0);
const cell = (x, y) => xs[y][x];
 
// intercalate :: String if-> (nRows[String] ===-> nCols) {String
const nsintercalate = range(0,s nCols - 1);=>
xs => xs.join(s);
return [zipWith(cell, ns, ns), zipWith(cell, ns, reverse(ns))];
} else return [
[],
[]
];
};
 
// zipWithisInt :: (aInt -> b -> c) -> [a] -> [b] -> [c]Bool
const zipWithisInt = (f,x xs,=> ys)x =>== {Math.floor(x);
const ny = ys.length;
return (xs.length <= ny ? xs : xs.slice(0, ny))
.map((x, i) => f(x, ys[i]));
}
 
// reversejustifyRight :: [a]Int -> [a]Char -> String -> String
const reversejustifyRight = (xs)n => xs.slice(0)cFiller => s =>
n > s.reverselength ? ()
s.padStart(n, cFiller)
) : s;
 
// rangemap :: Int(a -> Intb) -> [Inta] -> [b]
const rangemap = (m,f n)=> xs =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
 
// pred :: Enum a => a -> a
const pred = x => x - 1;
 
// replicate :: Int -> a -> [a]
const replicate = n => x =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + ix);
 
// allreverse :: ([a -> Bool)] -> [a] -> Bool
const allreverse = (f, xs) => xs.every(f);
'string' !== typeof xs ? (
xs.slice(0).reverse()
) : xs.split('').reverse().join('');
 
// show :: a -> String
const show = x => JSON.stringify(x);
 
// justifyRightstr :: Inta -> Char -> Text -> TextString
const justifyRightstr = (n,x cFiller,=> strTextx.toString() =>;
n > strText.length ? (
(cFiller.repeat(n) + strText)
.slice(-n)
) : strText;
 
// sum :: [Num] -> Num
// TEST -----------------------------------------------------------------
const sum = xs => xs.reduce((a, x) => a + x, 0);
 
// transpose :: [[a]] -> [[a]]
//return doubleEvenMagicSquare(8)
const transpose = xs =>
xs[0].map((_, iCol) => xs.map((row) => row[iCol]));
 
// unlines :: [String] -> String
return [4, 8, 12]
const unlines = .map(nxs => {xs.join('\n');
 
const lines = doubleEvenMagicSquare(n);
// zipWith :: (a -> b -> c) const-> sums[a] =-> lines.concat([b] -> [c]
const zipWith = f => xs => ys transpose(lines)=>
xs.concatslice(diagonals(lines))
0, Math.min(xs.length, ys.length)
).map(xs => xs.reduce((ax, bi) => a + b, 0f(x)(ys[i]));
const sum = sums[0];
return [
"Order: " + n.toString(),
"Summing to: " + sum.toString(),
"Row, column and diagonal sums checked: " +
all(x => x === sum, sums)
.toString() + '\n',
lines.map(
xs => xs.map(
x => justifyRight(3, ' ', x.toString())
)
.join(' '))
.join('\n')
].join('\n')
})
.join('\n\n');
})();</lang>
 
// MAIN ------------------------------------------------
return main();
})();</syntaxhighlight>
{{Out}}
<pre>Order: 4
Line 1,414 ⟶ 1,952:
24 122 123 21 20 126 127 17 16 130 131 13
133 11 10 136 137 7 6 140 141 3 2 144</pre>
 
=={{header|jq}}==
{{trans|Wren}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
<syntaxhighlight lang="jq">def lpad($len):
def l: tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
if type == "array" then map(l) else l end;
 
def magicSquareDoublyEven:
if . < 4 or .%4 != 0 then "Base must be a positive multiple of 4" | error else . end
| . as $n
# pattern of count-up vs count-down zones
| [1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1] as $bits
| ($n * $n) as $size
| ($n / 4 | floor) as $mult # how many multiples of 4
| { i:0, result: null }
| reduce range(0; $n) as $r (.;
reduce range(0; $n) as $c (.;
( (($c/$mult)|floor) + (($r/$mult)|floor) * 4) as $bitPos
| .result[$r][$c] =
(if ($bits[$bitPos] != 0) then .i + 1 else $size - .i end)
| .i += 1 ) )
| .result ;
 
# Input: the order
def task:
. as $n
| (.*.|tostring|length+1) as $width
| (magicSquareDoublyEven[] | lpad($width) | join(" ")),
"\nMagic constant for order \($n): \(($n*$n + 1) * $n / 2)\n\n" ;
 
8, 12 | task</syntaxhighlight>
{{out}}
<pre>
1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
Magic constant for order 8: 260
 
 
1 2 3 141 140 139 138 137 136 10 11 12
13 14 15 129 128 127 126 125 124 22 23 24
25 26 27 117 116 115 114 113 112 34 35 36
108 107 106 40 41 42 43 44 45 99 98 97
96 95 94 52 53 54 55 56 57 87 86 85
84 83 82 64 65 66 67 68 69 75 74 73
72 71 70 76 77 78 79 80 81 63 62 61
60 59 58 88 89 90 91 92 93 51 50 49
48 47 46 100 101 102 103 104 105 39 38 37
109 110 111 33 32 31 30 29 28 118 119 120
121 122 123 21 20 19 18 17 16 130 131 132
133 134 135 9 8 7 6 5 4 142 143 144
 
Magic constant for order 12: 870
 
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">#using v0.6Printf
 
function magicsquaredoubleeven(order::Int)
Line 1,443 ⟶ 2,045:
end
println()
end</langsyntaxhighlight>
 
{{out}}
Line 1,481 ⟶ 2,083:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.0
 
fun magicSquareDoublyEven(n: Int): Array<IntArray> {
Line 1,509 ⟶ 2,111:
}
println("\nMagic constant ${(n * n + 1) * n / 2}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,528 ⟶ 2,130:
For all three kinds of Magic Squares(Odd, singly and doubly even)<br />
See [[Magic_squares/Lua]].
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import bitops, sequtils, strutils
 
type Square = seq[seq[int]]
 
func magicSquareDoublyEven(n: int): Square =
## Build a magic square of doubly even order.
 
assert n >= 4 and (n and 3) == 0, "base must be a positive multiple of 4."
result = newSeqWith(n, newSeq[int](n))
 
const bits = 0b1001_0110_0110_1001 # Pattern of count-up vs count-down zones.
let size = n * n
let mult = n div 4 # How many multiples of 4.
 
var i = 0
for r in 0..<n:
for c in 0..<n:
let bitPos = c div mult + r div mult * 4
result[r][c] = if bits.testBit(bitPos): i + 1 else: size - i
inc i
 
 
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 = 8
echo magicSquareDoublyEven(n)
echo "Magic constant = ", n * (n * n + 1) div 2</syntaxhighlight>
 
{{out}}
<pre> 1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
Magic constant = 260</pre>
 
=={{header|PARI/GP}}==
 
A magic one-liner:
<langsyntaxhighlight lang="parigp">magicsquare(n)=matrix(n,n,i,j,k=i+j*n-n;if(bitand(38505,2^((j-1)%4*4+(i-1)%4)),k,n*n+1-k))</langsyntaxhighlight>
 
Output:<pre>magicsquare(8)
Line 1,557 ⟶ 2,207:
 
See [[Magic_squares/Perl|Magic squares/Perl]] for a general magic square generator.
<lang perl></lang>
 
=={{header|Perl 6}}==
See [[Magic_squares/Perl_6|Magic squares/Perl 6]] for a general magic square generator.
{{out}}
With a parameter of 8:
<pre> 1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
The magic number is 260</pre>
With a parameter of 12:
<pre> 1 2 3 141 140 139 138 137 136 10 11 12
13 14 15 129 128 127 126 125 124 22 23 24
25 26 27 117 116 115 114 113 112 34 35 36
108 107 106 40 41 42 43 44 45 99 98 97
96 95 94 52 53 54 55 56 57 87 86 85
84 83 82 64 65 66 67 68 69 75 74 73
72 71 70 76 77 78 79 80 81 63 62 61
60 59 58 88 89 90 91 92 93 51 50 49
48 47 46 100 101 102 103 104 105 39 38 37
109 110 111 33 32 31 30 29 28 118 119 120
121 122 123 21 20 19 18 17 16 130 131 132
133 134 135 9 8 7 6 5 4 142 143 144
 
The magic number is 870</pre>
 
=={{header|Phix}}==
{{trans|C++}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant t = {{1,1,0,0},
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
{1,1,0,0},
<span style="color: #008080;">constant</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{0,0,1,1},
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{0,0,1,1}}
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
 
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}}</span>
function magic_square(integer n)
if n<4 or mod(n,4)!=0 then return false end if
<span style="color: #008080;">function</span> <span style="color: #000000;">magic_square</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
sequence square = repeat(repeat(0,n),n)
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">4</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;">4</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">false</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
integer i = 0
<span style="color: #004080;">sequence</span> <span style="color: #000000;">square</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>
for r=1 to n do
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for c=1 to n do
<span style="color: #008080;">for</span> <span style="color: #000000;">r</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>
square[r,c] = iff(t[mod(r,4)+1,mod(c,4)+1]?i+1:n*n-i)
<span style="color: #008080;">for</span> <span style="color: #000000;">c</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>
i += 1
<span style="color: #000000;">square</span><span style="color: #0000FF;">[</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">[</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;">4</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]?</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</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;">i</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return square
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">square</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
procedure check(sequence sq)
integer n = length(sq)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">)</span>
integer magic = n*(n*n+1)/2
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">)</span>
integer bd = 0, fd = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">magic</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>
for i=1 to length(sq) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">bd</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fd</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
if sum(sq[i])!=magic then ?9/0 end if
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if sum(columnize(sq,i))!=magic then ?9/0 end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])!=</span><span style="color: #000000;">magic</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
bd += sq[i,i]
<span style="color: #008080;">if</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">))!=</span><span style="color: #000000;">magic</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
fd += sq[n-i+1,n-i+1]
<span style="color: #000000;">bd</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
end for
<span style="color: #000000;">fd</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
if bd!=magic or fd!=magic then ?9/0 end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #008080;">if</span> <span style="color: #000000;">bd</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">magic</span> <span style="color: #008080;">or</span> <span style="color: #000000;">fd</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">magic</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
--for i=4 to 16 by 4 do
for i=8 to 8 by 4 do
<span style="color: #000080;font-style:italic;">--for i=4 to 16 by 4 do</span>
sequence square = magic_square(i)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">8</span> <span style="color: #008080;">to</span> <span style="color: #000000;">8</span> <span style="color: #008080;">by</span> <span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
printf(1,"maqic square of order %d, sum: %d\n", {i,sum(square[i])})
<span style="color: #004080;">sequence</span> <span style="color: #000000;">square</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">magic_square</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
string fmt = sprintf("%%%dd",length(sprintf("%d",i*i)))
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"maqic square of order %d, sum: %d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">square</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])})</span>
pp(square,{pp_Nest,1,pp_IntFmt,fmt,pp_StrFmt,1,pp_Pause,0})
<span style="color: #004080;">string</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%%%dd"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)))</span>
check(square)
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">square</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: #000000;">fmt</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>
end for</lang>
<span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #000000;">square</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,645 ⟶ 2,267:
=={{header|PureBasic}}==
{{trans|FreeBasic}}
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.i MagicN(n.i)
ProcedureReturn n*(n*n+1)/2
EndProcedure
Line 1,712 ⟶ 2,334:
DblEvenMagicSquare(n)
n=0
ForEver</langsyntaxhighlight>
{{out}}<pre>Input [4,8,12..n] (0=Exit)
>8
Line 1,729 ⟶ 2,351:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">
def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
Line 1,757 ⟶ 2,379:
 
printsq(MagicSquareDoublyEven(8))
</syntaxhighlight>
</lang>
{{out}}<pre>
1 2 62 61 60 59 7 8
Line 1,776 ⟶ 2,398:
Generating test results and a magic square in the form of a wiki table:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Magic squares of doubly even order'''
 
from itertools import chain, repeat
Line 1,946 ⟶ 2,568:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Row sums: [260, 260, 260, 260, 260, 260, 260, 260]
Line 2,025 ⟶ 2,647:
|64
|}
 
=={{header|R}}==
 
Translation of the magic square code example from [https://math.nist.gov/javanumerics/jama/ Jama], which is released to the public domain. This includes all three cases.
 
<syntaxhighlight lang="r">magic <- function(n) {
if (n %% 2 == 1) {
p <- (n + 1) %/% 2 - 2
ii <- seq(n)
outer(ii, ii, function(i, j) n * ((i + j + p) %% n) + (i + 2 * (j - 1)) %% n + 1)
} else if (n %% 4 == 0) {
p <- n * (n + 1) + 1
ii <- seq(n)
outer(ii, ii, function(i, j) ifelse((i %/% 2 - j %/% 2) %% 2 == 0, p - n * i - j, n * (i - 1) + j))
} else {
p <- n %/% 2
q <- p * p
k <- (n - 2) %/% 4 + 1
a <- Recall(p)
a <- rbind(cbind(a, a + 2 * q), cbind(a + 3 * q, a + q))
ii <- seq(p)
jj <- c(seq(k - 1), seq(length.out=k - 2, to=n))
m <- a[ii, jj]; a[ii, jj] <- a[ii + p, jj]; a[ii + p, jj] <- m
jj <- c(1, k)
m <- a[k, jj]; a[k, jj] <- a[k + p, jj]; a[k + p, jj] <- m
a
}
}</syntaxhighlight>
 
'''Example'''
 
<pre>> magic(8)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 64 2 3 61 60 6 7 57
[2,] 9 55 54 12 13 51 50 16
[3,] 17 47 46 20 21 43 42 24
[4,] 40 26 27 37 36 30 31 33
[5,] 32 34 35 29 28 38 39 25
[6,] 41 23 22 44 45 19 18 48
[7,] 49 15 14 52 53 11 10 56
[8,] 8 58 59 5 4 62 63 1</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
See [[Magic_squares/Raku|Magic squares/Raku]] for a general magic square generator.
{{out}}
With a parameter of 8:
<pre> 1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
The magic number is 260</pre>
With a parameter of 12:
<pre> 1 2 3 141 140 139 138 137 136 10 11 12
13 14 15 129 128 127 126 125 124 22 23 24
25 26 27 117 116 115 114 113 112 34 35 36
108 107 106 40 41 42 43 44 45 99 98 97
96 95 94 52 53 54 55 56 57 87 86 85
84 83 82 64 65 66 67 68 69 75 74 73
72 71 70 76 77 78 79 80 81 63 62 61
60 59 58 88 89 90 91 92 93 51 50 49
48 47 46 100 101 102 103 104 105 39 38 37
109 110 111 33 32 31 30 29 28 118 119 120
121 122 123 21 20 19 18 17 16 130 131 132
133 134 135 9 8 7 6 5 4 142 143 144
 
The magic number is 870</pre>
 
=={{header|REXX}}==
Line 2,032 ⟶ 2,727:
"Marked" numbers &nbsp; (via the &nbsp; '''diag''' &nbsp; subroutine) &nbsp; indicate that those (sequentially generated) numbers don't get
<br>swapped &nbsp; (and thusly, stay in place in the magic square).
<langsyntaxhighlight lang="rexx">/*REXX program constructs a magic square of doubly even sides (a size divisible by 4).*/
n= 8; s= n%4; L= n%2-s+1; w= length(n**2) /*size; small sq; low middle; # width*/
@.= 0; H= n%2+s /*array default; high middle. */
call gen /*generate a grid in numerical order. */
call diag /*mark numbers on both diagonals. */
Line 2,056 ⟶ 2,751:
do c=1 for n; if @.r.c<0 then iterate; call max# /*find max number.*/
parse value -@.a.b (-@.r.c) with @.r.c @.a.b /*swap two values.*/
end /*c*/
end /*r*/; return
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
corn: do r=1 for n; if r>s & r<=n-s then iterate /*"corner boxen", size≡S*/
do c=1 for n; if c>s & c<=n-s then iterate; @.r.c= -@(r,c); end /*cnegate*/
end /*rc*/
end /*r*/; return</syntaxhighlight>
return</lang>
'''{{out|output''' |text=&nbsp; when using the default input:}}
<pre>
1 2 62 61 60 59 7 8
Line 2,080 ⟶ 2,774:
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">def double_even_magic_square(n)
raise ArgumentError, "Need multiple of four" if n%4 > 0
block_size, max = n/4, n*n
Line 2,097 ⟶ 2,791:
end
 
puts to_string(double_even_magic_square(8))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,107 ⟶ 2,801:
24 23 43 44 45 46 18 17
16 15 51 52 53 54 10 9
57 58 6 5 4 3 63 64
</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.")
{
Ok(arg) if arg >= 4 && arg % 4 == 0 => arg,
Err(e) => panic!(e),
_ => panic!("Argument must be a positive multiple of 4."),
};
 
let mc = (n * n + 1) * n / 2;
println!("Magic constant: {}\n", mc);
let bits = 0b1001_0110_0110_1001u32;
let size = n * n;
let width = size.to_string().len() + 1;
let mult = n / 4;
let mut i = 0;
for r in 0..n {
for c in 0..n {
let bit_pos = c / mult + (r / mult) * 4;
print!(
"{e:>w$}",
e = if bits & (1 << bit_pos) != 0 {
i + 1
} else {
size - i
},
w = width
);
i += 1;
}
println!();
}
}</syntaxhighlight>
{{out}}
<pre>
Magic constant: 260
 
1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
</pre>
Line 2,112 ⟶ 2,858:
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/bdTcGF3/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/gLhkwHHlRO6rPXg9U7MDzg Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">object MagicSquareDoublyEven extends App {
private val n = 8
 
Line 2,134 ⟶ 2,880:
println(f"---%nMagic constant: ${(n * n + 1) * n / 2}%d")
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func double_even_magic_square(n) {
assert(n%4 == 0, "Need multiple of four")
var (bsize, max) = (n/4, n*n)
Line 2,152 ⟶ 2,899:
}
 
say format_matrix(double_even_magic_square(8))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,164 ⟶ 2,911:
57 58 6 5 4 3 63 64
</pre>
 
=={{header|Stata}}==
 
{{trans|R}}
 
<syntaxhighlight lang="stata">mata
function magic(n) {
if (mod(n,2)==1) {
p = (n+1)/2-2
a = J(n,n,.)
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++) {
a[i,j] = n*mod(i+j+p,n)+mod(i+2*j-2,n)+1
}
}
} else if (mod(n,4)==0) {
p = n^2+n+1
a = J(n,n,.)
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++) {
a[i,j] = mod(floor(i/2)-floor(j/2),2)==0 ? p-n*i-j : n*(i-1)+j
}
}
} else {
p = n/2
q = p*p
k = (n-2)/4+1
a = magic(p)
a = a,a:+2*q\a:+3*q,a:+q
i = 1..p
j = 1..k-1
if (k>2) j = j,n-k+3..n
m = a[i,j]; a[i,j] = a[i:+p,j]; a[i:+p,j] = m
j = 1,k
m = a[k,j]; a[k,j] = a[k:+p,j]; a[k:+p,j] = m
}
return(a)
}
end</syntaxhighlight>
 
<pre>. mata magic(8)
1 2 3 4 5 6 7 8
+-----------------------------------------+
1 | 64 2 3 61 60 6 7 57 |
2 | 9 55 54 12 13 51 50 16 |
3 | 17 47 46 20 21 43 42 24 |
4 | 40 26 27 37 36 30 31 33 |
5 | 32 34 35 29 28 38 39 25 |
6 | 41 23 22 44 45 19 18 48 |
7 | 49 15 14 52 53 11 10 56 |
8 | 8 58 59 5 4 62 63 1 |
+-----------------------------------------+</pre>
 
=={{header|VBScript}}==
{{trans|Java}}
<langsyntaxhighlight lang="vb">' Magic squares of doubly even order
n=8 'multiple of 4
pattern="1001011001101001"
Line 2,184 ⟶ 2,983:
wscript.echo l
Next 'r
wscript.echo "Magic constant=" & (n*n+1)*n/2</langsyntaxhighlight>
{{out}}
<pre>Magic square : 8 x 8
Line 2,199 ⟶ 2,998:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module MagicSquares
 
Function MagicSquareDoublyEven(n As Integer) As Integer(,)
Line 2,247 ⟶ 3,046:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre> 1 2 62 61 60 59 7 8
Line 2,259 ⟶ 3,058:
 
Magic constant: 260</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Conv, Fmt
 
var magicSquareDoublyEven = Fn.new { |n|
if (n < 4 || n%4 != 0) Fiber.abort("Base must be a positive multiple of 4")
 
// pattern of count-up vs count-down zones
var bits = Conv.atoi("1001011001101001", 2)
var size = n * n
var mult = (n/4).floor // how many multiples of 4
var result = List.filled(n, null)
for (i in 0...n) result[i] = List.filled(n, 0)
var i = 0
for (r in 0...n) {
for (c in 0...n) {
var bitPos = (c/mult).floor + (r/mult).floor * 4
result[r][c] = ((bits & (1<<bitPos)) != 0) ? i + 1 : size - i
i = i + 1
}
}
return result
}
 
var n = 8
for (ia in magicSquareDoublyEven.call(n)) {
for (i in ia) Fmt.write("$2d ", i)
System.print()
}
System.print("\nMagic constant %((n * n + 1) * n / 2)")</syntaxhighlight>
 
{{out}}
<pre>
1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
Magic constant 260
</pre>
 
=={{header|zkl}}==
{{trans|Java}}
<langsyntaxhighlight lang="zkl">class MagicSquareDoublyEven{
fcn init(n){ var result=magicSquareDoublyEven(n) }
fcn toString{
Line 2,286 ⟶ 3,131:
}
}
MagicSquareDoublyEven(8).println();</langsyntaxhighlight>
{{out}}
<pre>
Anonymous user