Magic squares of doubly even order: Difference between revisions

Added Algol 68
(Added 11l)
(Added Algol 68)
Line 194:
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.
<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</lang>
{{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>
 
3,038

edits