Magic squares of odd order: Difference between revisions

Added Easylang
m (→‎{{header|Phix}}: pp_StrFmt tweaks)
(Added Easylang)
 
(40 intermediate revisions by 22 users not shown)
Line 18:
 
;Task
 
For any odd   '''N''',   [[wp:Magic square#Method_for_constructing_a_magic_square_of_odd_order|generate a magic square]] with the integers   ''' 1''' ──► '''N''',   and show the results here.
 
Line 33 ⟶ 32:
; See also:
* MathWorld™ entry: [http://mathworld.wolfram.com/MagicSquare.html Magic_square]
* [http://www.1728.org/magicsq1.htm Odd Magic Squares (1728.org)]<br><br>
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F magic(n)
L(row) 1..n
print(((1..n).map(col -> @n * ((@row + col - 1 + @n I/ 2) % @n)
+ ((@row + 2 * col - 2) % @n) + 1)).map(cell -> String(cell).rjust(String(@n ^ 2).len)).join(‘ ’))
print("\nAll sum to magic number #.".format((n * n + 1) * n I/ 2))
 
L(n) (5, 3, 7)
print("\nOrder #.\n=======".format(n))
magic(n)</syntaxhighlight>
 
{{out}}
<pre>
Order 5
=======
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
 
All sum to magic number 65
 
Order 3
=======
8 1 6
3 5 7
4 9 2
 
All sum to magic number 15
 
Order 7
=======
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
 
All sum to magic number 175
</pre>
 
=={{header|360 Assembly}}==
{{trans|C}}
<langsyntaxhighlight lang="360asm">* Magic squares of odd order - 20/10/2015
MAGICS CSECT
USING MAGICS,R15 set base register
Line 78 ⟶ 124:
PG DC CL92' ' buffer
YREGS
END MAGICS</langsyntaxhighlight>
{{out}}
<pre>
Line 93 ⟶ 139:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Command_Line;
 
procedure Magic_Square is
Line 127 ⟶ 173:
Ada.Text_IO.New_Line;
end loop;
end Magic_Square;</langsyntaxhighlight>
 
{{out}}
Line 149 ⟶ 195:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># construct a magic square of odd order #
PROC magic square = ( INT order ) [,]INT:
IF NOT ODD order OR order < 1
Line 207 ⟶ 253:
 
# test the magic square generation #
FOR order BY 2 TO 7 DO print square( magic square( order ) ) OD</langsyntaxhighlight>
{{out}}
<pre>
Line 233 ⟶ 279:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% construct a magic square of odd order - as a procedure can't return an %
% array, the caller must supply one that is big enough %
Line 309 ⟶ 355:
end for_i
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 334 ⟶ 380:
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
{{trans|C}}
<syntaxhighlight lang="apl">magic←{⍵{+/1,(1 ⍺⍺)×⍺(⍺⍺|1+⊢+2×⊣)⍵,⍺⍺-⍵+1}/¨⎕IO-⍨⍳⍵ ⍵}</syntaxhighlight>
{{out}}
<pre> magic¨ 1 3 5 7
1 2 9 4 2 23 19 15 6 2 45 39 33 27 21 8
7 5 3 14 10 1 22 18 18 12 6 49 36 30 24
6 1 8 21 17 13 9 5 34 28 15 9 3 46 40
8 4 25 16 12 43 37 31 25 19 13 7
20 11 7 3 24 10 4 47 41 35 22 16
26 20 14 1 44 38 32
42 29 23 17 11 5 48 </pre>
=={{header|AppleScript}}==
{{trans|JavaScript}}
Line 341 ⟶ 400:
to allow for first class functions and closures.
 
<syntaxhighlight lang="applescript">---------------- MAGIC SQUARE OF ODD ORDER ---------------
<lang AppleScript>-- oddMagicSquare :: Int -> [[Int]]
 
-- oddMagicSquare :: Int -> [[Int]]
on oddMagicSquare(n)
cond(if 0 < (n mod 2) > 0, ¬then
cycleRows(transpose(cycleRows(table(n)))), ¬
else
missing value)
missing value
end if
end oddMagicSquare
 
 
-- TEST -----------------------------------------------------------------------
--------------------------- TEST -------------------------
on run
-- Orders 3, 5, 11
Line 402 ⟶ 466:
 
 
-- GENERIC FUNCTIONS --------------------------------------- GENERIC FUNCTIONS -------------------
 
-- intercalate :: Text -> [Text] -> Text
Line 475 ⟶ 539:
end transpose
 
 
-- WIKI DISPLAY ---------------------------------------------------------------
 
----------------------- WIKI DISPLAY ---------------------
 
-- formattedTable :: [[Int]] -> String
Line 510 ⟶ 576:
g
end if
end cond</langsyntaxhighlight>
{{Out}}
magic(3)
Line 564 ⟶ 630:
| 66 || 67 || 79 || 91 || 103 || 115 || 6 || 18 || 30 || 42 || 54
|}
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">oddMagicSquare: function [n][
ensure -> and? odd? n
n >= 0
map 1..n 'i [
map 1..n 'j [
(n * ((i + (j - 1) + n / 2) % n)) +
(((i - 2) + 2 * j) % n) + 1
]
]
]
 
loop [3 5 7] 'n [
print ["Size:" n ", Magic sum:" n*(1+n*n)/2 "\n"]
loop oddMagicSquare n 'row [
loop row 'item [
prints pad to :string item 3
]
print ""
]
print ""
]</syntaxhighlight>
 
{{out}}
 
<pre>Size: 3 , Magic sum: 15
8 1 6
3 5 7
4 9 2
 
Size: 5 , Magic sum: 65
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
 
Size: 7 , Magic sum: 175
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">
msgbox % OddMagicSquare(5)
msgbox % OddMagicSquare(7)
Line 606 ⟶ 723:
return str
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 628 ⟶ 745:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MAGIC_SQUARES_OF_ODD_ORDER.AWK
BEGIN {
Line 699 ⟶ 816:
printf("\t: %d diagonal bottom left to top right\n",total)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 737 ⟶ 854:
==={{header|Applesoft BASIC}}===
Even if the code works for any odd number, N=9 is the maximum for a 40 column wide screen. Line <code>130</code> is a user defined modulo function, and <code>140</code> helps calculate the addends for the number that will go in the current position.
<syntaxhighlight lang="applesoft basic">
<lang Applesoft BASIC>
100 :
110 REM MAGIC SQUARE OF ODD ORDER
Line 751 ⟶ 868:
260 NEXT I
270 PRINT "MAGIC CONSTANT: ";N * (N * N + 1) / 2
</syntaxhighlight>
</lang>
{{out}}
<pre>ENTER N: 5
Line 760 ⟶ 877:
20 11 7 3 24
MAGIC CONSTANT: 65</pre>
 
==={{header|BASIC256}}===
{{trans|Liberty BASIC}}
<syntaxhighlight lang="freebasic">arraybase 1
global m
 
call magicSquare(5)
call magicSquare(17)
end
 
subroutine magicSquare(n)
redim m(n,n)
inc = 1
cont = 1
row = 1
col = (n+1) / 2
while cont <= n*n
m[row,col] = cont
cont += 1
if inc < n then
inc += 1
row -= 1
col += 1
if row <> 0 then
if col > n then col = 1
else
row = n
end if
else
inc = 1
row += 1
end if
end while
call printSquare(n)
end subroutine
 
subroutine printSquare(n)
#Arbitrary limit to fit width of A4 paper
if n < 23 then
print
print n; " x "; n; " Magic Square --- ";
print "Magic constant is "; int((n*n+1)/2*n)
for row = 1 to n
for col = 1 to n
print rjust(string(m[row,col]),4);
next col
print
next row
else
print "Magic Square will not fit on one sheet of paper."
end if
end subroutine</syntaxhighlight>
{{out}}
<pre>5 x 5 Magic Square --- Magic constant is 65
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
 
17 x 17 Magic Square --- Magic constant is 2465
155 174 193 212 231 250 269 288 1 20 39 58 77 96 115 134 153
173 192 211 230 249 268 287 17 19 38 57 76 95 114 133 152 154
191 210 229 248 267 286 16 18 37 56 75 94 113 132 151 170 172
209 228 247 266 285 15 34 36 55 74 93 112 131 150 169 171 190
227 246 265 284 14 33 35 54 73 92 111 130 149 168 187 189 208
245 264 283 13 32 51 53 72 91 110 129 148 167 186 188 207 226
263 282 12 31 50 52 71 90 109 128 147 166 185 204 206 225 244
281 11 30 49 68 70 89 108 127 146 165 184 203 205 224 243 262
10 29 48 67 69 88 107 126 145 164 183 202 221 223 242 261 280
28 47 66 85 87 106 125 144 163 182 201 220 222 241 260 279 9
46 65 84 86 105 124 143 162 181 200 219 238 240 259 278 8 27
64 83 102 104 123 142 161 180 199 218 237 239 258 277 7 26 45
82 101 103 122 141 160 179 198 217 236 255 257 276 6 25 44 63
100 119 121 140 159 178 197 216 235 254 256 275 5 24 43 62 81
118 120 139 158 177 196 215 234 253 272 274 4 23 42 61 80 99
136 138 157 176 195 214 233 252 271 273 3 22 41 60 79 98 117
137 156 175 194 213 232 251 270 289 2 21 40 59 78 97 116 135</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">100 cls
110 sub magicsq(size,filename$ = "")
120 if (size and 1) = 0 or size < 3 then
130 print
140 print "error: size is not odd or size is smaller then 3"
160 exit sub
170 endif
180 ' filename$ <> "" then save magic square in a file
190 ' filename$ can contain directory name
200 ' if filename$ exist it will be overwriten, no error checking
210 dim sq(size,size)' array to hold square
220 ' start in the middle of the first row
230 nr = 1
240 x = size-int(size/2)
250 y = 1
260 max = size*size
270 ' create format string for using
280 for c = 1 to len(str$(max))+1 : frmt$ = frmt$+"#" : next c
290 'main loop for creating magic square
300 do
310 if sq(x,y) = 0 then
320 sq(x,y) = nr
330 if nr mod size = 0 then
340 y = y+1
350 else
360 x = x+1
370 y = y-1
380 endif
390 nr = nr+1
400 endif
410 if x > size then
420 x = 1
430 do while sq(x,y) <> 0
440 x = x+1
450 loop
460 endif
470 if y < 1 then
480 y = size
490 do while sq(x,y) <> 0
500 y = y-1
510 loop
520 endif
530 loop until nr > max
540 ' printing square's bigger than 19 result in a wrapping of the line
550 print "Odd magic square size: ";size;"*";size
560 print "The magic sum = ";int((max+1)/2)*size
570 print
580 for y = 1 to size
590 for x = 1 to size
600 print using "####";val(sq(x,y));
610 next x
620 print
630 next y
640 print
650 ' output magic square to a file with the name provided
660 if filename$ <> "" then
670 nr = freefile
680 open filename$ for output as #1
690 print #1,"Odd magic square size: ";size;"*";size
700 print #1,"The magic sum = ";int((max+1)/2)*size
710 print #1,
720 for y = 1 to size
730 for x = 1 to size
740 print #1,using frmt$;sq(x,y);
750 next x
760 print #1,
770 next y
780 endif
790 close #1
800 end sub
810 input "Enter N: ",number
820 magicsq(number)
830 end</syntaxhighlight>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' version 23-06-2015
' compile with: fbc -s console
 
Sub magicsq(size As Integer, filename As String ="")
 
If (size And 1) = 0 Or size < 3 Then
Print : Beep ' alert
Print "error: size is not odd or size is smaller then 3"
Sleep 3000,1 'wait 3 seconds, ignore key press
Exit Sub
End If
 
' filename <> "" then save magic square in a file
' filename can contain directory name
' if filename exist it will be overwriten, no error checking
 
Dim As Integer sq(size,size) ' array to hold square
' start in the middle of the first row
Dim As Integer nr = 1, x = size - (size \ 2), y = 1
Dim As Integer max = size * size
' create format string for using
Dim As String frmt = String(Len(Str(max)) +1, "#")
 
' main loop for creating magic square
Do
If sq(x, y) = 0 Then
sq(x, y) = nr
If nr Mod size = 0 Then
y += 1
Else
x += 1
y -= 1
End If
nr += 1
End If
If x > size Then
x = 1
Do While sq(x,y) <> 0
x += 1
Loop
End If
If y < 1 Then
y = size
Do While sq(x,y) <> 0
y -= 1
Loop
EndIf
Loop Until nr > max
 
' printing square's bigger than 19 result in a wrapping of the line
Print "Odd magic square size:"; size; " *"; size
Print "The magic sum ="; ((max +1) \ 2) * size
Print
 
For y = 1 To size
For x = 1 To size
Print Using frmt; sq(x,y);
Next
Print
Next
print
 
' output magic square to a file with the name provided
If filename <> "" Then
nr = FreeFile
Open filename For Output As #nr
Print #nr, "Odd magic square size:"; size; " *"; size
Print #nr, "The magic sum ="; ((max +1) \ 2) * size
Print #nr,
 
For y = 1 To size
For x = 1 To size
Print #nr, Using frmt; sq(x,y);
Next
Print #nr,
Next
End If
Close
 
End Sub
 
' ------=< MAIN >=------
 
magicsq(5)
magicsq(11)
' the next line will also print the square to a file called: magic_square_19.txt
magicsq(19, "magic_square_19.txt")
 
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre>Odd magic square size: 5 * 5 Odd magic square size: 11 * 11
The magic sum = 65 The magic sum = 671
17 24 1 8 15 68 81 94 107 120 1 14 27 40 53 66
23 5 7 14 16 80 93 106 119 11 13 26 39 52 65 67
4 6 13 20 22 92 105 118 10 12 25 38 51 64 77 79
10 12 19 21 3 104 117 9 22 24 37 50 63 76 78 91
11 18 25 2 9 116 8 21 23 36 49 62 75 88 90 103
7 20 33 35 48 61 74 87 89 102 115
19 32 34 47 60 73 86 99 101 114 6
31 44 46 59 72 85 98 100 113 5 18
43 45 58 71 84 97 110 112 4 17 30
55 57 70 83 96 109 111 3 16 29 42
Only the first 2 square shown. 56 69 82 95 108 121 2 15 28 41 54</pre>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
{{trans|IS-BASIC}}
<syntaxhighlight lang="qbasic">100 REM Magic squares of odd order
110 INPUT "The square order: ", N
115 'INPUT "The square order:"; N ' for MSX Basic
120 IF (N AND 1) = 0 OR N < 3 THEN PRINT "error: size is not odd or size is smaller then 3" : GOTO 100
130 FOR I = 1 TO N
140 FOR J = 1 TO N
150 PRINT USING " ###"; ((I*2-J+N-1) MOD N) * N + ((I*2+J-2) MOD N) + 1;
160 NEXT J
170 PRINT
180 NEXT I
190 PRINT "The magic number is: "; N * (N^2+1) / 2</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight IS-BASIClang="qbasic">100 PROGRAM "MagicN.bas"
110 DO
120 INPUT PROMPT "The square order: ":N
Line 772 ⟶ 1,174:
180 PRINT
190 NEXT
200 PRINT "The magic number is:";N*(N^2+1)/2</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">Dim m(1,1)
 
Call magicSquare 5
Call magicSquare 17
 
End
 
Sub magicSquare n
ReDim m(n,n)
inc = 1
count = 1
row = 1
col=(n+1)/2
While count <= n*n
m(row,col) = count
count = count + 1
If inc < n Then
inc = inc + 1
row = row - 1
col = col + 1
If row <> 0 Then
If col > n Then col = 1
Else
row = n
End If
Else
inc = 1
row = row + 1
End If
Wend
Call printSquare n
End Sub
 
Sub printSquare n
'Arbitrary limit to fit width of A4 paper
If n < 23 Then
Print n;" x ";n;" Magic Square --- ";
Print "Magic constant is ";Int((n*n+1)/2*n)
For row = 1 To n
For col = 1 To n
Print Using("####",m(row,col));
Next col
Print
Print
Next row
Else
Notice "Magic Square will not fit on one sheet of paper."
End If
End Sub </syntaxhighlight>
{{Out}}
<pre>5 x 5 Magic Square --- Magic constant is 65
17 24 1 8 15
 
23 5 7 14 16
 
4 6 13 20 22
 
10 12 19 21 3
 
11 18 25 2 9
 
17 x 17 Magic Square --- Magic constant is 2465
155 174 193 212 231 250 269 288 1 20 39 58 77 96 115 134 153
 
173 192 211 230 249 268 287 17 19 38 57 76 95 114 133 152 154
 
191 210 229 248 267 286 16 18 37 56 75 94 113 132 151 170 172
 
209 228 247 266 285 15 34 36 55 74 93 112 131 150 169 171 190
 
227 246 265 284 14 33 35 54 73 92 111 130 149 168 187 189 208
 
245 264 283 13 32 51 53 72 91 110 129 148 167 186 188 207 226
 
263 282 12 31 50 52 71 90 109 128 147 166 185 204 206 225 244
 
281 11 30 49 68 70 89 108 127 146 165 184 203 205 224 243 262
 
10 29 48 67 69 88 107 126 145 164 183 202 221 223 242 261 280
 
28 47 66 85 87 106 125 144 163 182 201 220 222 241 260 279 9
 
46 65 84 86 105 124 143 162 181 200 219 238 240 259 278 8 27
 
64 83 102 104 123 142 161 180 199 218 237 239 258 277 7 26 45
 
82 101 103 122 141 160 179 198 217 236 255 257 276 6 25 44 63
 
100 119 121 140 159 178 197 216 235 254 256 275 5 24 43 62 81
 
118 120 139 158 177 196 215 234 253 272 274 4 23 42 61 80 99
 
136 138 157 176 195 214 233 252 271 273 3 22 41 60 79 98 117
 
137 156 175 194 213 232 251 270 289 2 21 40 59 78 97 116 135
</pre>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
{{trans|IS-BASIC}}
<syntaxhighlight lang="qbasic">100 REM Magic squares of odd order
110 INPUT "The square order:"; N
120 IF (N AND 1) = 0 OR N < 3 THEN PRINT "error: size is not odd or size is smaller then 3" : GOTO 100
130 FOR I = 1 TO N
140 FOR J = 1 TO N
150 PRINT USING " ###"; ((I*2-J+N-1) MOD N) * N + ((I*2+J-2) MOD N) + 1;
160 NEXT J
170 PRINT
180 NEXT I
190 PRINT "The magic number is:"; N * (N^2+1) / 2</syntaxhighlight>
 
==={{header|PureBasic}}===
{{trans|Pascal}}
<syntaxhighlight lang="purebasic">#N=9
Define.i i,j
 
If OpenConsole("Magic squares")
PrintN("The square order is: "+Str(#N))
For i=1 To #N
For j=1 To #N
Print(RSet(Str((i*2-j+#N-1) % #N*#N + (i*2+j-2) % #N+1),5))
Next
PrintN("")
Next
PrintN("The magic number is: "+Str(#N*(#N*#N+1)/2))
EndIf
Input()</syntaxhighlight>
{{out}}
<pre>The square order is: 9
2 75 67 59 51 43 35 27 10
22 14 6 79 71 63 46 38 30
42 34 26 18 1 74 66 58 50
62 54 37 29 21 13 5 78 70
73 65 57 49 41 33 25 17 9
12 4 77 69 61 53 45 28 20
32 24 16 8 81 64 56 48 40
52 44 36 19 11 3 76 68 60
72 55 47 39 31 23 15 7 80
The magic number is: 369</pre>
 
==={{header|QB64}}===
<syntaxhighlight lang="qb64">_Title "Magic Squares of Odd Order"
'$Dynamic
DefLng A-Z
Dim Shared As Long m(1, 1)
 
Call magicSquare(5)
Call magicSquare(15)
 
Sleep
System
 
Sub magicSquare (n As Integer)
Dim As Integer inc, count, row, col
 
If (n < 3) Or (n And 1) <> 1 Then n = 3
ReDim m(n, n)
inc = 1
count = 1
row = 1
col = (n + 1) / 2
While count <= n * n
m(row, col) = count
count = count + 1
If inc < n Then
inc = inc + 1
row = row - 1
col = col + 1
If row <> 0 Then
If col > n Then col = 1
Else
row = n
End If
Else
inc = 1
row = row + 1
End If
Wend
Call printSquare(n)
End Sub
 
Sub printSquare (n As Integer)
Dim As Integer row, col
'Arbitrary limit ensures a fit within console window
'Can be any size that fits within your computers memory limits
If n < 21 Then
Print "Order "; n; " Magic Square constant is "; Str$(Int((n * n + 1) / 2 * n))
For row = 1 To n
For col = 1 To n
Print Using "####"; m(row, col);
Next col
Print
' Print
Next row
End If
End Sub</syntaxhighlight>
{{Out}}
<pre>Order 5 Magic Square constant is 65
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
Order 15 Magic Square constant is 1695
122 139 156 173 190 207 224 1 18 35 52 69 86 103 120
138 155 172 189 206 223 15 17 34 51 68 85 102 119 121
154 171 188 205 222 14 16 33 50 67 84 101 118 135 137
170 187 204 221 13 30 32 49 66 83 100 117 134 136 153
186 203 220 12 29 31 48 65 82 99 116 133 150 152 169
202 219 11 28 45 47 64 81 98 115 132 149 151 168 185
218 10 27 44 46 63 80 97 114 131 148 165 167 184 201
9 26 43 60 62 79 96 113 130 147 164 166 183 200 217
25 42 59 61 78 95 112 129 146 163 180 182 199 216 8
41 58 75 77 94 111 128 145 162 179 181 198 215 7 24
57 74 76 93 110 127 144 161 178 195 197 214 6 23 40
73 90 92 109 126 143 160 177 194 196 213 5 22 39 56
89 91 108 125 142 159 176 193 210 212 4 21 38 55 72
105 107 124 141 158 175 192 209 211 3 20 37 54 71 88
106 123 140 157 174 191 208 225 2 19 36 53 70 87 104
</pre>
 
==={{header|uBasic/4tH}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="text">' ------=< MAIN >=------
Proc _magicsq(5)
Proc _magicsq(11)
End
 
_magicsq Param (1) Local (4)
 
' reset the array
For b@ = 0 to 255
@(b@) = 0
Next
 
If ((a@ % 2) = 0) + (a@ < 3) + (a@ > 15) Then
Print "error: size is not odd or size is smaller then 3 or bigger than 15"
Return
EndIf
 
' start in the middle of the first row
b@ = 1
c@ = a@ - (a@ / 2)
d@ = 1
e@ = a@ * a@
 
' main loop for creating magic square
Do
If @(c@*a@+d@) = 0 Then
@(c@*a@+d@) = b@
If (b@ % a@) = 0 Then
d@ = d@ + 1
Else
c@ = c@ + 1
d@ = d@ - 1
EndIf
b@ = b@ + 1
EndIf
If c@ > a@ Then
c@ = 1
Do While @(c@*a@+d@) # 0
c@ = c@ + 1
Loop
EndIf
If d@ < 1 Then
d@ = a@
Do While @(c@*a@+d@) # 0
d@ = d@ - 1
Loop
EndIf
Until b@ > e@
Loop
 
Print "Odd magic square size: "; a@; " * "; a@
Print "The magic sum = "; ((e@+1) / 2) * a@
Print
 
For d@ = 1 To a@
For c@ = 1 To a@
Print Using "____"; @(c@*a@+d@);
Next
Print
Next
Print
Return</syntaxhighlight>
{{out}}
<pre>Odd magic square size: 5 * 5
The magic sum = 65
 
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
 
Odd magic square size: 11 * 11
The magic sum = 671
 
68 81 94 107 120 1 14 27 40 53 66
80 93 106 119 11 13 26 39 52 65 67
92 105 118 10 12 25 38 51 64 77 79
104 117 9 22 24 37 50 63 76 78 91
116 8 21 23 36 49 62 75 88 90 103
7 20 33 35 48 61 74 87 89 102 115
19 32 34 47 60 73 86 99 101 114 6
31 44 46 59 72 85 98 100 113 5 18
43 45 58 71 84 97 110 112 4 17 30
55 57 70 83 96 109 111 3 16 29 42
56 69 82 95 108 121 2 15 28 41 54
 
 
0 OK, 0:64</pre>
 
==={{header|VBA}}===
{{trans|C}}
Works with Excel VBA.
<syntaxhighlight lang="vb">Sub magicsquare()
'Magic squares of odd order
Const n = 9
Dim i As Integer, j As Integer, v As Integer
Debug.Print "The square order is: " & n
For i = 1 To n
For j = 1 To n
Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Next j
Next i
Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2
End Sub 'magicsquare</syntaxhighlight>
 
==={{header|Visual Basic}}===
{{trans|C}}
{{works with|Visual Basic|VB6 Standard}}
<syntaxhighlight lang="vb">Sub magicsquare()
'Magic squares of odd order
Const n = 9
Dim i As Integer, j As Integer, v As Integer
Debug.Print "The square order is: " & n
For i = 1 To n
For j = 1 To n
v = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Debug.Print Right(Space(5) & v, 5);
Next j
Debug.Print
Next i
Debug.Print "The magic number is: " & n * (n * n + 1) \ 2
End Sub 'magicsquare
</syntaxhighlight>
{{out}}
<pre>The square order is: 9
2 75 67 59 51 43 35 27 10
22 14 6 79 71 63 46 38 30
42 34 26 18 1 74 66 58 50
62 54 37 29 21 13 5 78 70
73 65 57 49 41 33 25 17 9
12 4 77 69 61 53 45 28 20
32 24 16 8 81 64 56 48 40
52 44 36 19 11 3 76 68 60
72 55 47 39 31 23 15 7 80
The magic number is: 369</pre>
 
==={{header|Visual Basic .NET}}===
{{works with|Visual Basic .NET|2011}}
<syntaxhighlight lang="vbnet">Sub magicsquare()
'Magic squares of odd order
Const n = 9
Dim i, j, v As Integer
Console.WriteLine("The square order is: " & n)
For i = 1 To n
For j = 1 To n
v = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Console.Write(" " & Right(Space(5) & v, 5))
Next j
Console.WriteLine("")
Next i
Console.WriteLine("The magic number is: " & n * (n * n + 1) \ 2)
End Sub 'magicsquare</syntaxhighlight>
{{out}}
<pre>The square order is: 9
2 75 67 59 51 43 35 27 10
22 14 6 79 71 63 46 38 30
42 34 26 18 1 74 66 58 50
62 54 37 29 21 13 5 78 70
73 65 57 49 41 33 25 17 9
12 4 77 69 61 53 45 28 20
32 24 16 8 81 64 56 48 40
52 44 36 19 11 3 76 68 60
72 55 47 39 31 23 15 7 80
The magic number is: 369</pre>
 
==={{header|Yabasic}}===
{{trans|Liberty BASIC}}
<syntaxhighlight lang="freebasic">magicSquare(5)
magicSquare(17)
end
 
sub magicSquare(n)
redim m(n,n)
inc = 1
cont = 1
row = 1
col = (n+1) / 2
while cont <= n*n
m(row,col) = cont
cont = cont + 1
if inc < n then
inc = inc + 1
row = row - 1
col = col + 1
if row <> 0 then
if col > n col = 1
else
row = n
end if
else
inc = 1
row = row + 1
end if
end while
printSquare(n)
end sub
 
sub printSquare(n)
//Arbitrary limit to fit width of A4 paper
if n < 23 then
print "\n", n, " x ", n, " Magic Square --- ";
print "Magic constant is ", int((n*n+1)/2*n)
for row = 1 to n
for col = 1 to n
print m(row,col) using("####");
next col
print
next row
else
print "Magic Square will not fit on one sheet of paper."
end if
end sub</syntaxhighlight>
{{out}}
<pre>5 x 5 Magic Square --- Magic constant is 65
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
 
17 x 17 Magic Square --- Magic constant is 2465
155 174 193 212 231 250 269 288 1 20 39 58 77 96 115 134 153
173 192 211 230 249 268 287 17 19 38 57 76 95 114 133 152 154
191 210 229 248 267 286 16 18 37 56 75 94 113 132 151 170 172
209 228 247 266 285 15 34 36 55 74 93 112 131 150 169 171 190
227 246 265 284 14 33 35 54 73 92 111 130 149 168 187 189 208
245 264 283 13 32 51 53 72 91 110 129 148 167 186 188 207 226
263 282 12 31 50 52 71 90 109 128 147 166 185 204 206 225 244
281 11 30 49 68 70 89 108 127 146 165 184 203 205 224 243 262
10 29 48 67 69 88 107 126 145 164 183 202 221 223 242 261 280
28 47 66 85 87 106 125 144 163 182 201 220 222 241 260 279 9
46 65 84 86 105 124 143 162 181 200 219 238 240 259 278 8 27
64 83 102 104 123 142 161 180 199 218 237 239 258 277 7 26 45
82 101 103 122 141 160 179 198 217 236 255 257 276 6 25 44 63
100 119 121 140 159 178 197 216 235 254 256 275 5 24 43 62 81
118 120 139 158 177 196 215 234 253 272 274 4 23 42 61 80 99
136 138 157 176 195 214 233 252 271 273 3 22 41 60 79 98 117
137 156 175 194 213 232 251 270 289 2 21 40 59 78 97 116 135</pre>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
rem Magic squares of odd order
setlocal EnableDelayedExpansion
Line 793 ⟶ 1,660:
set /a w=n*(n*n+1)/2
echo The magic number is: %w%
pause</langsyntaxhighlight>
{{out}}
<pre>The square order is: 9
Line 810 ⟶ 1,677:
=={{header|bc}}==
{{works with|GNU bc}}
<langsyntaxhighlight lang="bc">define magic_constant(n) {
return(((n * n + 1) / 2) * n)
}
Line 838 ⟶ 1,705:
}
 
temp = print_magic_square(5)</langsyntaxhighlight>
 
{{Out}}
Line 847 ⟶ 1,714:
10 12 19 21 3
11 18 25 2 9</pre>
 
=={{header|BCPL}}==
{{trans|C}}
<syntaxhighlight lang="bcpl">get "libhdr"
 
let cell(n, x, y) = f(n, n-x-1, y)*n + f(n, x, y) + 1
and f(n, x, y) = (x + y*2 + 1) rem n
 
let magic(n) be
$( writef("Magic square of order %N with constant %N:*N", n, (n*n+1)/2*n)
for y = 0 to n-1
$( for x = 0 to n-1 do writed(cell(n, x, y), 4)
wrch('*N')
$)
wrch('*N')
$)
 
let start() be for n = 1 to 7 by 2 do magic(n)</syntaxhighlight>
{{out}}
<pre>Magic square of order 1 with constant 1:
1
 
Magic square of order 3 with constant 15:
2 9 4
7 5 3
6 1 8
 
Magic square of order 5 with constant 65:
2 23 19 15 6
14 10 1 22 18
21 17 13 9 5
8 4 25 16 12
20 11 7 3 24
 
Magic square of order 7 with constant 175:
2 45 39 33 27 21 8
18 12 6 49 36 30 24
34 28 15 9 3 46 40
43 37 31 25 19 13 7
10 4 47 41 35 22 16
26 20 14 1 44 38 32
42 29 23 17 11 5 48</pre>
 
=={{header|Befunge}}==
{{trans|C}}
The size, ''n'', is specified by the first value on the stack.
<langsyntaxhighlight lang="befunge">500p0>:::00g%00g\-1-\00g/2*+1+00g%00g*\:00g%v
@<$<_^#!-*:g00:,+9!%g00:+1.+1+%g00+1+*2/g00\<</langsyntaxhighlight>
 
{{out}}
Line 860 ⟶ 1,769:
8 4 25 16 12
20 11 7 3 24 </pre>
 
=={{header|BQN}}==
{{trans|C}}
<syntaxhighlight lang="bqn">Magic ← {𝕏{+´1∾1‿𝕗×𝕨(𝕗|1+⊢+2×⊣)𝕩∾𝕗-𝕩+1}´¨↕2⥊𝕩}
Magic¨ ⟨1,3,5,7⟩</syntaxhighlight>
{{out}}
<pre>┌─
· ┌─ ┌─ ┌─ ┌─
╵ 1 ╵ 2 9 4 ╵ 2 23 19 15 6 ╵ 2 45 39 33 27 21 8
┘ 7 5 3 14 10 1 22 18 18 12 6 49 36 30 24
6 1 8 21 17 13 9 5 34 28 15 9 3 46 40
┘ 8 4 25 16 12 43 37 31 25 19 13 7
20 11 7 3 24 10 4 47 41 35 22 16
┘ 26 20 14 1 44 38 32
42 29 23 17 11 5 48
┘</pre>
 
=={{header|C}}==
Generates an associative magic square. If the size is larger than 3, the square is also [http://en.wikipedia.org/wiki/Pandiagonal_magic_square panmagic].
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
Line 890 ⟶ 1,816:
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>$ ./magic 5
Line 902 ⟶ 1,828:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <vector>
using namespace std;
 
class magicSqrMagicSquare
{
public:
magicSqrMagicSquare(int d) {: sqr = (d*d,0;), }sz(d)
~magicSqr() { if( sqr ) delete [] sqr; }
 
void create( int d )
{
ifassert( sqr d&1) delete [] sqr;
if( !( d & 1 ) ) d++; sz = d;
sqr = new int[sz * sz];
memset( sqr, 0, sz * sz * sizeof( int ) );
fillSqr();
}
 
void display()
{
cout << "Odd Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr; cvr << sz * sz;
cvr << sz * sz;
int l = cvr.str().size();
 
for( int y = 0; y < sz; y++ )
{
Line 935 ⟶ 1,858:
for( int x = 0; x < sz; x++ )
cout << setw( l + 2 ) << sqr[yy + x];
 
cout << "\n";
}
cout << "\n\n";
}
 
private:
void fillSqr()
Line 959 ⟶ 1,881:
}
}
 
int magicNumber()
{ return sz * ( ( sz * sz ) + 1 ) / 2; }
 
void inc( int& a )
{ if( ++a == sz ) a = 0; }
 
void dec( int& a )
{ if( --a < 0 ) a = sz - 1; }
 
bool checkPos( int x, int y )
{ return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
 
bool isInside( int s )
{ return ( s < sz && s > -1 ); }
 
vector<int*> sqr;
int sz;
};
 
int main( int argc, char* argv[] )
{
magicSqrMagicSquare s(7);
s.create( 5 );
s.display();
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Odd Magic Square: 5 x 5
It's Magic Sum is: 65
 
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
 
Odd Magic Square: 7 x 7
It's Magic Sum is: 175
Line 1,009 ⟶ 1,921:
22 31 40 49 2 11 20
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">magic_square = cluster is create, unparse, magic_number
rep = array[array[int]]
 
create = proc (order: int) returns (cvt) signals (invalid)
if order<1 cor order//2 = 0 then signal invalid end
sq: rep := rep$fill_copy(1, order, array[int]$fill(1, order, 0))
x: int := (order+1)/2
y: int := 1
for i: int in int$from_to(1, order**2) do
sq[y][x] := i
next_x: int := inc(sq,x)
next_y: int := dec(sq,y)
if sq[next_y][next_x]=0
then x, y := next_x, next_y
else y := inc(sq,y)
end
end
return(sq)
end create
 
inc = proc (sq: rep, co: int) returns (int)
order: int := rep$size(sq)
if co=order then return(1) else return(co+1) end
end inc
 
dec = proc (sq: rep, co: int) returns (int)
order: int := rep$size(sq)
if co=1 then return(order) else return(co-1) end
end dec
unparse = proc (sq: cvt) returns (string)
order: int := rep$size(sq)
col_size: int := string$size(int$unparse(order ** 2)) + 1
ss: stream := stream$create_output()
for y: int in int$from_to(1, order) do
for x: int in int$from_to(1, order) do
stream$putright(ss, int$unparse(sq[y][x]), col_size)
end
stream$putl(ss, "")
end
return(stream$get_contents(ss))
end unparse
 
magic_number = proc (sq: cvt) returns (int)
order: int := rep$size(sq)
n: int := 0
for x: int in int$from_to(1, order) do n := n + sq[1][x] end
return(n)
end magic_number
end magic_square
 
 
print_magic_square = proc (order: int)
po: stream := stream$primary_output()
ms: magic_square := magic_square$create(order)
stream$putl(po, "Magic square of order "
|| int$unparse(order)
|| " with magic number "
|| int$unparse(magic_square$magic_number(ms))
|| ": ")
stream$putl(po, magic_square$unparse(ms))
end print_magic_square
 
start_up = proc ()
for n: int in int$from_to_by(1, 7, 2) do
print_magic_square(n)
end
end start_up</syntaxhighlight>
{{out}}
<pre>Magic square of order 1 with magic number 1:
1
 
Magic square of order 3 with magic number 15:
8 1 6
3 5 7
4 9 2
 
Magic square of order 5 with magic number 65:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
 
Magic square of order 7 with magic number 175:
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun magic-square (n)
(loop for i from 1 to n
collect
Line 1,031 ⟶ 2,038:
(let* ((size (length (write-to-string (* n n))))
(format-str (format NIL "~~{~~{~~~ad~~^ ~~}~~%~~}~~%" size)))
(format T format-str (magic-square n))))</langsyntaxhighlight>
 
{{Out}}
Line 1,042 ⟶ 2,049:
11 18 25 2 9</pre>
 
=={{header|Cowgol}}==
{{trans|C}}
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub magic(n: uint16) is
sub f(x: uint16, y: uint16): (r: uint16) is
r := (x + y*2 + 1) % n;
end sub;
sub cell(x: uint16, y: uint16): (c: uint16) is
c := f(n-x-1, y)*n + f(x, y) + 1;
end sub;
var y: uint16 := 0;
while y < n loop
var x: uint16 := 0;
loop
print_i16(cell(x, y));
x := x + 1;
if x == n then
print_nl();
break;
else
print_char('\t');
end if;
end loop;
y := y + 1;
end loop;
print_nl();
end sub;
 
var n: uint16 := 1;
while n <= 7 loop
print("Magic square of order ");
print_i16(n);
print(" with constant ");
print_i16((n*n+1)/2*n);
print(":\n");
magic(n);
n := n + 2;
end loop;</syntaxhighlight>
{{out}}
<pre>Magic square of order 1 with constant 1:
1
 
Magic square of order 3 with constant 15:
2 9 4
7 5 3
6 1 8
 
Magic square of order 5 with constant 65:
2 23 19 15 6
14 10 1 22 18
21 17 13 9 5
8 4 25 16 12
20 11 7 3 24
 
Magic square of order 7 with constant 175:
2 45 39 33 27 21 8
18 12 6 49 36 30 24
34 28 15 9 3 46 40
43 37 31 25 19 13 7
10 4 47 41 35 22 16
26 20 14 1 44 38 32
42 29 23 17 11 5 48</pre>
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">void main(in string[] args)
{
import std.stdio, std.conv, std.range, std.algorithm, std.exception;
Line 1,067 ⟶ 2,139:
 
writeln("\nMagic constant: ", ((n * n + 1) * n) / 2);
}}</langsyntaxhighlight>
{{out}}
<pre>17 24 1 8 15
Line 1,079 ⟶ 2,151:
===Alternative Version===
{{trans|C}}
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.string, std.range, std.algorithm;
 
uint[][] magicSquare(immutable uint n) pure nothrow @safe
Line 1,144 ⟶ 2,216:
stderr.writefln("Requires n odd and larger than 0.");
return 1;
}</langsyntaxhighlight>
{{out}}
<pre>15 8 1 24 17
Line 1,153 ⟶ 2,225:
 
Magic constant: 65</pre>
 
=={{header|Delphi}}==
See [https://www.rosettacode.org/wiki/Magic_squares_of_odd_order#Pascal Pascal].
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc inc(word n, order) word: if n=order-1 then 0 else n+1 fi corp
proc dec(word n, order) word: if n=0 then order-1 else n-1 fi corp
 
proc odd_magic_square([*,*]word square) void:
word order, x, nx, y, ny, i;
order := dim(square,1);
for x from 0 upto order-1 do
for y from 0 upto order-1 do
square[x,y] := 0
od
od;
x := order/2;
y := 0;
for i from 1 upto order*order do
square[x,y] := i;
nx := inc(x,order);
ny := dec(y,order);
if square[nx,ny] = 0 then
x := nx;
y := ny
else
y := inc(y,order)
fi
od
corp
 
proc digit_count(word n) word:
word count;
count := 0;
while n > 0 do
count := count + 1;
n := n / 10
od;
count
corp
 
proc print_magic_square([*,*]word square) void:
word order, max, col_size, magic, x, y;
order := dim(square,1);
max := order*order;
col_size := digit_count(max) + 1;
magic := 0;
for x from 0 upto order-1 do magic := magic + square[x,0] od;
writeln("Magic square of order ",order," with magic number ",magic,":");
for y from 0 upto order-1 do
for x from 0 upto order-1 do write(square[x,y]:col_size) od;
writeln()
od;
writeln()
corp
 
proc main() void:
[1,1]word sq1;
[3,3]word sq3;
[5,5]word sq5;
[7,7]word sq7;
odd_magic_square(sq1);
odd_magic_square(sq3);
odd_magic_square(sq5);
odd_magic_square(sq7);
print_magic_square(sq1);
print_magic_square(sq3);
print_magic_square(sq5);
print_magic_square(sq7)
corp</syntaxhighlight>
{{out}}
<pre>Magic square of order 1 with magic number 1:
1
 
Magic square of order 3 with magic number 15:
8 1 6
3 5 7
4 9 2
 
Magic square of order 5 with magic number 65:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
 
Magic square of order 7 with magic number 175:
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20</pre>
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
func f n x y .
return (x + y * 2 + 1) mod n
.
numfmt 0 3
proc msqr n . .
for i = 0 to n - 1
for j = 0 to n - 1
write f n (n - j - 1) i * n + f n j i + 1
.
print ""
.
.
msqr 5
</syntaxhighlight>
{{out}}
<pre>
2 23 19 15 6
14 10 1 22 18
21 17 13 9 5
8 4 25 16 12
20 11 7 3 24
</pre>
 
=={{header|EchoLisp}}==
The '''make-ms''' procedure allows to construct different magic squares for a same n, by modifying the grid filling moves. (see MathWorld reference)
<langsyntaxhighlight lang="scheme">
(lib 'matrix)
 
Line 1,189 ⟶ 2,387:
(array-print ms))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,234 ⟶ 2,432:
28 2 32 13 36 17 47
10 40 21 44 25 6 29
</pre>
 
=={{header|EDSAC order code}}==
<syntaxhighlight lang="edsac">
[Magic squares of odd order, for Rosetta Code.
EDSAC program, Initial Orders 2.]
 
[The entries in a magic square of side n can be written as n*u + v + 1,
where u and v range independently over 0, ..., n - 1.
Let the cells be labelled by (x, y) coordinates, where
x = column (left = 0), y = row (bottom = 0).
If n is odd then magic squares can be constructed by setting
u = c*x + d*y + h (mod n)
v = e*x + f*y + k (mod n)
where c, d, e, f, h, k are suitable constants.
Define m = (n - 1)/2. The values of c, ..., k for various methods
of construction are as follows:
c, d, e, f, h, k
Bachet: m + 1, m, m + 1, m + 1, m, 0
De la Loubere: 1, 2m, 2, 2m, m, 0
Conway (lozenge): 1, 2m, 1, 1, m, m + 1
Rosetta Code C: 2m, 2m - 1, 1, 2m - 1, 2m - 1, 2m
------------------------------------------------------------------------------]
[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 + high-level subroutine]
 
[Main routine + non-library subroutine]
E25K TM GK
[Rows are printed in the order y = n - 1 (top) to y = 0 (bottom).
Row y = n is a fictitious row used during initialization.]
[Locations set up by main routine; some are changed by subroutine]
[0] PF [m]
[1] PF [n]
[2] PF [n^2]
[3] PF [n * 2^11]
[4] PF [c, changed to n*(n - c) = dec to n*u on inc(x)]
[5] PF [d, changed to n*d = dec to n*u on dec(y)]
[6] PF [e, changed to n - e = dec to v on inc(x)]
[7] PF [f = dec to v when dec(y)]
[8] PF [h, changed to n*u for start of current row]
[9] PF [k, changed to v for start of current row]
[Locations used only by subroutine]
[10] PF [n*u]
[11] PF [v]
[12] PF [x count]
[13] PF [y count]
 
[Subroutine to print magic square, using parameters set up by main routine.]
[14] A3F T77@ [plant return link as usual]
A80@ T1F [set to print leading zeros as spaces]
A1@ S6@ T6@ [replace e by n - e]
A1@ S4@ T4@ [replace c by n - c]
[Multiply certain values by n. To maintain the integer scaling,
products have to be shifted 16 left before storing.]
H3@ V8@ [acc := (n << 11)*h]
L8F T8@ [shift 5 more left and store n*h]
V5@ L8F T5@ [similarly n*d]
V4@ L8F T4@ [similarly n*(n - c)]
[Loop round rows y := n - 1 down to 0. At the moment y = n.]
S1@ T13@ [initialize negative count of rows (y values)]
[Start of a row. Here acc = 0]
[36] S1@ T12@ [inititialize negative count of columns (x values)]
A8@ S5@ [decrement n*u by n*d]
E42@ [skip if n*u >= 0]
A2@ [else inc n*u by n^2]
[42] U8@ [store updated n*u for next time]
T10@ [also copy to initialize this row]
A9@ S7@ [decrement v by f]
E48@ [skip if v >= 0]
A1@ [else inc v by n]
[48] U9@ [store updated v at for next time]
U11@ [also copy to initialize this row]
[Next column. Here acc = v]
[50] A10@ A78@ TF [cell value v + n*u + 1 to 0F for printing]
[53] A53@ GN [call subroutine to print cell value]
A12@ A78@ [increment negative column count]
E70@ [jump if row is complete]
T12@ [else update count]
A10@ S4@ [dec n*u by n*n - c)]
E63@ [skip if n*U >= 0]
A2@ [else inc n*u by n^2]
[63] T10@ [store updated n*u for next time]
A11@ S6@ [dec v by n - e]
E68@ [skip if v >= 0]
A1@ [else inc v by n]
[68] U11@ [store updated v, keep v in acc]
E50@ [loop back for next cell in row]
[Row finished]
[70] O81@ O82@ [print CR LF]
A13@ A78@ [inc negative row count]
E77@ [exit if done all rows]
T13@ E36@ [else update count and loop back]
[77] ZF [(planted) jump back to caller]
[Constants]
[78] PD [17-bit 1]
[79] K4096F [null]
[80] !F [space]
[81] @F [carriage return]
[82] &F [line feed]
[83] P10F [for testing number of phone pulses]
[Strings for printing. K2048F sets letters mode; K4096F is EDSAC null.]
[84] K2048FMFAFGFIFCF!FSFQFUFAFRFEF!FOFFF!FOFRFDFEFRF!F#FWF*FMF#FZFQF@F&FK4096F
[117] K2048FDFIFAFLF!FMF!F#FKFPF!F*FTFOF!FCFAFNFCFEFLF#FLF@F&FK4096F
[144] K2048FBFAFCFHFEFTF#FCF@F&FK4096F
[156] K2048FDFEF!FLFAF!FLFOFUFBFEFRFEF#FCF@F&FK4096F
[175] K2048FCFOFNFWFAFYF#FCF@F&FK4096F
[187] K2048FRFOFSFEFTFTFAF!FCFOFDFEF!FCF#FCF@F&FK4096F
 
[Enter with acc = 0]
[207] A207@ GH A84@ [print heading]
[210] A210@ GH A117@ [prompt user to dial m, where n = 2m + 1]
ZF [halt program; restarts when user dials]
[Here acc holds number of pulses in address field.
Number of pulses = 10 if user dialled '0', else = number that user dialled.]
S83@ E292@ [test for '0', jump to exit if so]
A83@ [restore acc after test]
L512F [shift m to top 5 bits for printing]
UF [temp to 0F]
OF O81@ O82@ [print digit m, plus CR LF]
R512F [restore m in address field, same as 2m right-justified]
A78@ U1@ [make and store n = 2m + 1, right justified]
RD T@ [make and store m right-justified]
A1@ L512F T3@ [make and store n << 11]
H3@ V1@ [acc := (n << 11)*n]
L8F [shift 5 left for integer scaling]
T2@ [store n^2]
[Bachet's method]
[234] A234@ GH A144@ [print name of method]
A@ U5@ U8@ [d, h := m]
A78@ U4@ U6@ T7@ [c, e, f := m + 1]
T9@ [k := 0]
[245] A245@ G14@ [call s/r to print square]
[De la Loubere's (miscalled Siamese) method]
[247] A247@ GH A156@ [print name of method]
A78@ U4@ [c := 1]
LD T6@ [e := 2]
A@ U8@ [h := m]
LD U5@ T7@ [d, f := 2m]
T9@ [k := 0 ]
[260] A260@ G14@ [call s/r to print square]
[Conway's lozenge method turns out to be of this type]
[262] A262@ GH A175@ [print name of method]
A78@ U4@ U6@ U7@ [c, e, f := 1]
A@ T9@ [k := m + 1]
A@ U8@ [h := m]
LD T5@ [d := 2m]
[275] A275@ G14@ [call s/r to print square]
[C solution on Rosetta Code website]
[277] A277@ GH A187@ [print name of method]
A78@ T6@ [e := 1]
A@ LD U4@ U9@ [c, k := 2m]
S78@ U5@ U7@ T8@ [d, f, h := 2m - 1]
[290] A290@
G14@ [call s/r to print square]
[292] O79@ [done; print null to flush teleprinter buffer]
ZF [halt the machine]
E25K TH
[Subroutine to print a string.
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
 
E25K TN
[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]
GKA3FT34@A1FT7FS35@T6FT4#FAFT4FH36@V4FRDA4#FR1024FH37@E23@O7FA2F
T6FT5FV4#FYFL8FT4#FA5FL1024FUFA6FG16@OFTFT7FA6FG17@ZFP4FZ219DTF
 
[================ M parameter again ================]
E25K TM GK
E207Z [define entry point]
PF [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
MAGIC SQUARE OF ORDER 2M+1
DIAL M (0 TO CANCEL)
2
BACHET:
3 16 9 22 15
20 8 21 14 2
7 25 13 1 19
24 12 5 18 6
11 4 17 10 23
DE LA LOUBERE:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
CONWAY:
18 24 5 6 12
22 3 9 15 16
1 7 13 19 25
10 11 17 23 4
14 20 21 2 8
ROSETTA CODE C:
2 23 19 15 6
14 10 1 22 18
21 17 13 9 5
8 4 25 16 12
20 11 7 3 24
</pre>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def odd_magic_square(n) when rem(n,2)==1 do
for i <- 0..n-1 do
Line 1,255 ⟶ 2,659:
IO.puts "\nSize #{n}, magic sum #{div(n*n+1,2)*n}"
RC.odd_magic_square(n) |> RC.print_square
end)</langsyntaxhighlight>
 
{{out}}
Line 1,286 ⟶ 2,690:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MAGIC_SQUARE
 
Line 1,380 ⟶ 2,784:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
Same as FreeBasic version
Line 1,400 ⟶ 2,804:
=={{header|Factor}}==
This solution uses the method from the paper linked in the J entry: http://www.jsoftware.com/papers/eem/magicsq.htm
<langsyntaxhighlight lang="factor">USING: formatting io kernel math math.matrices math.ranges
sequences sequences.extras ;
IN: rosetta-code.magic-squares-odd
Line 1,417 ⟶ 2,821:
"Magic number: %d\n\n" printf ;
 
3 5 11 [ show-square ] tri@</langsyntaxhighlight>
{{out}}
<pre>
Line 1,451 ⟶ 2,855:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program Magic_Square
implicit none
 
Line 1,480 ⟶ 2,884:
f2 = n * (1 + n * n) / 2
end function
end program</langsyntaxhighlight>
Output:
<pre>Magic Square Order: 15
Line 1,501 ⟶ 2,905:
Magic number = 1695</pre>
 
=={{header|FreeBASICFrink}}==
This program takes an order from command-line or requests an odd order from the user. It uses an algorithm from Dr. Crypton's column in Science Digest in the 1980s which the developer of Frink remembered and used to use by hand to create giant magic squares until his English teacher told him "don't do that in class."
<lang FreeBASIC>' version 23-06-2015
<syntaxhighlight lang="frink">order = length[ARGS] > 0 ? eval[ARGS@0] : undef
' compile with: fbc -s console
until isInteger[order] and order mod 2 == 1
order = eval[input["Enter order (must be odd): ", 3]]
 
a = new array[[order, order], undef]
Sub magicsq(size As Integer, filename As String ="")
x = order div 2
y = 0
 
for i = 1 to order^2
If (size And 1) = 0 Or size < 3 Then
{
Print : Beep ' alert
ny = (y - 1) mod order
Print "error: size is not odd or size is smaller then 3"
nx = (x + 1) mod order
Sleep 3000,1 'wait 3 seconds, ignore key press
if a@ny@nx != Exit Subundef
End If{
nx = x
ny = (y + 1) mod order
}
a@y@x = i
y = ny
x = nx
}
 
println[formatTable[a]]
' filename <> "" then save magic square in a file
println["Magic number is " + sum[a@0]]</syntaxhighlight>
' filename can contain directory name
' if filename exist it will be overwriten, no error checking
 
Dim As Integer sq(size,size) ' array to hold square
' start in the middle of the first row
Dim As Integer nr = 1, x = size - (size \ 2), y = 1
Dim As Integer max = size * size
' create format string for using
Dim As String frmt = String(Len(Str(max)) +1, "#")
 
' main loop for creating magic square
Do
If sq(x, y) = 0 Then
sq(x, y) = nr
If nr Mod size = 0 Then
y += 1
Else
x += 1
y -= 1
End If
nr += 1
End If
If x > size Then
x = 1
Do While sq(x,y) <> 0
x += 1
Loop
End If
If y < 1 Then
y = size
Do While sq(x,y) <> 0
y -= 1
Loop
EndIf
Loop Until nr > max
 
' printing square's bigger than 19 result in a wrapping of the line
Print "Odd magic square size:"; size; " *"; size
Print "The magic sum ="; ((max +1) \ 2) * size
Print
 
For y = 1 To size
For x = 1 To size
Print Using frmt; sq(x,y);
Next
Print
Next
print
 
' output magic square to a file with the name provided
If filename <> "" Then
nr = FreeFile
Open filename For Output As #nr
Print #nr, "Odd magic square size:"; size; " *"; size
Print #nr, "The magic sum ="; ((max +1) \ 2) * size
Print #nr,
 
For y = 1 To size
For x = 1 To size
Print #nr, Using frmt; sq(x,y);
Next
Print #nr,
Next
End If
Close
 
End Sub
 
' ------=< MAIN >=------
 
magicsq(5)
magicsq(11)
' the next line will also print the square to a file called: magic_square_19.txt
magicsq(19, "magic_square_19.txt")
 
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</lang>
{{out}}
<pre>
<pre>Odd magic square size: 5 * 5 Odd magic square size: 11 * 11
17 24 1 8 15
The magic sum = 65 The magic sum = 671
23 5 7 14 16
4 6 13 20 22
17 24 1 8 15 68 81 94 107 120 1 14 27 40 53 66
10 12 19 21 3
23 5 7 14 16 80 93 106 119 11 13 26 39 52 65 67
11 18 25 2 9
4 6 13 20 22 92 105 118 10 12 25 38 51 64 77 79
Magic number is 65
10 12 19 21 3 104 117 9 22 24 37 50 63 76 78 91
</pre>
11 18 25 2 9 116 8 21 23 36 49 62 75 88 90 103
7 20 33 35 48 61 74 87 89 102 115
19 32 34 47 60 73 86 99 101 114 6
31 44 46 59 72 85 98 100 113 5 18
43 45 58 71 84 97 110 112 4 17 30
55 57 70 83 96 109 111 3 16 29 42
Only the first 2 square shown. 56 69 82 95 108 121 2 15 28 41 54</pre>
 
=={{header|Go}}==
{{trans|C}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,653 ⟶ 2,982:
fmt.Println()
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,665 ⟶ 2,994:
====Translating imperative code====
{{trans|cpp}}
<langsyntaxhighlight lang="haskell">-- as a translation from imperative code, this is probably not a "good" implementation
import Data.List
 
Line 1,726 ⟶ 3,055:
putStr " = "
putStrLn $ show $ magicSum x
putStrLn $ display $ magicNumber x</langsyntaxhighlight>
 
====Transpose . cycled====
Line 1,732 ⟶ 3,061:
Defining the magic square as two applications of ('''transpose . cycled''') to a simply ordered square.
 
<syntaxhighlight lang Haskell="haskell">import DataControl.ListMonad (transpose, maximumByjoin)
import Data.List (maximumBy, transpose)
import Data.List.Split (chunksOf)
import Data.Ord (comparing)
 
 
magicSquare :: Int -> [[Int]]
magicSquare n
| 1 == mod n 2 = applyN 2 (transpose . cycled) $ plainSquare n
applyN 2 (transpose . cycled) $
plainSquare n
| otherwise = []
 
 
plainSquare :: Int -> [[Int]]
plainSquare = chunksOf <*> enumFromTo 1 . (^ 2)
 
 
-------------------------- TEST ---------------------------
main :: IO ()
main =
main = mapM_ putStrLn $ showSquare . magicSquare <$> [3, 5, 7]
mapM_ putStrLn $
showSquare . magicSquare <$> [3, 5, 7]
 
 
------------------------- GENERIC -------------------------
Line 1,753 ⟶ 3,094:
let n = length rows
d = quot n 2
in zipWith
(\d xs -> take n $ drop (n - d) (cycle xs))
[d, subtract 1 d .. - d]
rows
 
plainSquare :: Int -> [[Int]]
plainSquare = chunksOf <*> enumFromTo 1 . (^ 2)
 
-- FORMATTING ----------------------- FORMATTING ----------------------
justifyRight :: Int -> a -> [a] -> [a]
justifyRight n c = (drop . length) <*> (replicate n c ++<>)
 
showSquare :: Show a => [[a]] -> String
:: Show a
=> [[a]] -> String
showSquare rows =
( (\xs w -> unlines ((justifyRight w ' ' =<<) <$> xs))
let srows = fmap show <$> rows
w =<*> succ $. maximum (length. <$>fmap length concat. srows)join
)
in unlines $ fmap (justifyRight w ' ' =<<) srows</lang>
$ fmap show <$> rows</syntaxhighlight>
{{Out}}
<pre> 8 1 6
Line 1,794 ⟶ 3,131:
Encoding the traditional [[wp:Siamese_method|'Siamese' method]]
 
<syntaxhighlight lang="haskell">{-# LANGUAGE TupleSections #-}
<lang haskell>import qualified Data.Map.Strict as M
 
import Control.Monad (forM_)
import Data.MaybeList (isJustintercalate, fromJusttranspose)
import qualified Data.ListMap.Strict (transpose,as intercalate)M
import Data.Maybe (fromJust, isJust)
 
magic :: Int -> [[Int]]
magic = mapAsTable <*> siamMap
 
-- SIAMESE METHOD FUNCTIONS ------------------------------------- SIAMESE METHOD FUNCTIONS ---------------
 
-- Highest zero-based index of grid -> 'Siamese' indices keyed by coordinates
-- 'Siamese' indices keyed by coordinates
siamMap :: Int -> M.Map (Int, Int) Int
siamMap n =
if| odd n = go n
| then let hotherwise = quot nM.fromList 2[]
where
uBound = n - 1
go n = sPath uBound (M.fromList []) sPath(quot uBound sMap (x2, y0) h =1
where
let newMap = M.insert (x, y) h sMap
h in if y == uBound && x == quot uBoundn 2
uBound = n - then newMap1
sPath uBound sMap (x, y) h else sPath=
let newMap = M.insert (x, y) h uBoundsMap
in if y == uBound && x == quot uBound newMap2
then (nextSiam uBound sMap (x, y))newMap
(h + 1)else
in sPath uBound (M.fromList []) (quot uBound 2, 0) 1sPath
uBound
else M.fromList []
newMap
(nextSiam uBound sMap (x, y))
(succ h)
 
-- Highest index of square -> Siam xys so far -> xy -> next xy coordinate
-- next xy coordinate
nextSiam :: Int -> M.Map (Int, Int) Int -> (Int, Int) -> (Int, Int)
nextSiam uBound sMap (x, y) =
let alt (a, b)
| a > uBound && b < 0 = (uBound, 1) -- Top right corner ?
| a > uBound = (0,&& b) --< beyond0 right= edge(uBound, ?1)
| b < 0 = (a, uBound) -- abovebeyond topright edge ?
| isJust (M.lookup (a, b)> sMap)uBound = (a - 10, b + 2) -- already filled ?
-- above top edge ?
| b < 0 = (a, uBound)
-- already filled ?
| isJust (M.lookup (a, b) sMap) = (a - 1, b + 2)
| otherwise = (a, b) -- Up one, right one.
in alt (x + 1, y - 1)
 
-- DISPLAY AND TEST FUNCTIONS ------------------------------------ DISPLAY AND TEST FUNCTIONS --------------
 
-- Size of square -> integers keyed by coordinates -> rows of integers
-- -> rows of integers
mapAsTable :: Int -> M.Map (Int, Int) Int -> [[Int]]
mapAsTable nCols xyMap =
let axis = [0 .. nCols - 1]
in fmap (fromJust . flip M.lookup xyMap) <$>
(axis >>= \y -<$> [(axis >>= \xy -> [(x, y)] <$> axis])
 
checked :: [[Int]] -> (Int, Bool)
checked square =
let diagonals =
fmap (flip (zipWith (!!)) [0 ..]) . ((:) <*> (return . reverse))
. ( (:)
h:t = sum <$> square ++ transpose square ++ diagonals square
<*> (return . reverse)
in (h, all (h ==) t)
)
h : t =
sum <$> square
<> transpose square
<> diagonals square
in (h, all (h ==) t)
 
table :: String -> [[String]] -> [String]
table delim rows =
let justifyRight c n s = drop (length s) (replicate n c ++ s)
drop
in intercalate delim <$>
transpose (length s)
(replicate n c <> s)
((fmap =<< justifyRight ' ' . maximum . fmap length) <$> transpose rows)
in intercalate delim
<$> transpose
( (fmap =<< justifyRight ' ' . maximum . fmap length)
<$> transpose rows
)
 
main :: IO ()
main =
forM_ [3, 5, 7] $
\n -> do
let test = magic n
putStrLn $ unlines (table " " (fmap show <$> test))
print $ checked test
putStrLn ""</langsyntaxhighlight>
{{Out}}
<pre>8 1 6
Line 1,892 ⟶ 3,252:
 
This is a Unicon-specific solution because of the use of the <tt>[: ... :]</tt> construct.
<langsyntaxhighlight lang="unicon">procedure main(A)
n := integer(!A) | 3
write("Magic number: ",n*(n*n+1)/2)
Line 1,916 ⟶ 3,276:
s := *(n*n)+2
every r := !sq do every writes(right(!r,s)|"\n")
end</langsyntaxhighlight>
 
{{out}}
Line 1,934 ⟶ 3,294:
Based on http://www.jsoftware.com/papers/eem/magicsq.htm
 
<langsyntaxhighlight Jlang="j">ms=: i:@<.@-: |."0 1_1&|:^:2 >:@i.@,~</langsyntaxhighlight>
 
In other words, generate a square of counting integers, like this:
<langsyntaxhighlight Jlang="j"> >:@i.@,~ 3
1 2 3
4 5 6
7 8 9</langsyntaxhighlight>
 
Then generate a list of integers centering on 0 up to half of that value, like this:
<langsyntaxhighlight Jlang="j"> i:@<.@-: 3
_1 0 1</langsyntaxhighlight>
 
Finally, rotate each corresponding row and column of the table by the corresponding value in the list. We can use the same instructions to rotate both rows and columns if we transpose the matrix before rotating (and perform this transpose+rotate twice).
Line 1,950 ⟶ 3,310:
Example use:
 
<langsyntaxhighlight Jlang="j"> ms 5
9 15 16 22 3
20 21 2 8 14
Line 1,959 ⟶ 3,319:
65
~.+/ms 101
515201</langsyntaxhighlight>
 
Note also that an important feature of magic squares is that their diagonals sum the same way:
Or, based on suggestion by Marios Mamzeris on the talk page (which is similar but oriented different -- both rows and columns shifted somewhat):
 
<pre> 9+21+13+5+17
<lang J>msmm=: 1 + ((|."0 1 |:)^:2&i. ,~)</lang>
65
 
3+8+13+18+23
Example use:
65</pre>
 
<lang J> msmm 5
1 7 13 19 25
12 18 24 5 6
23 4 10 11 17
9 15 16 22 3
20 21 2 8 14
+/msmm 5
65 65 65 65 65</lang>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class MagicSquare {
 
public static void main(String[] args) {
Line 2,023 ⟶ 3,375:
return grid;
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,040 ⟶ 3,392:
( and referring to http://www.jsoftware.com/papers/eem/magicsq.htm )
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// n -> [[n]]
Line 2,125 ⟶ 3,477:
}
).join('\n\n')
})();</langsyntaxhighlight>
 
Output:
Line 2,187 ⟶ 3,539:
 
(2nd Haskell version: ''cycledRows . transpose . cycledRows'')
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// magicSquare :: Int -> [[Int]]
Line 2,259 ⟶ 3,611:
.map(magicSquare)
.map(xs => unlines(xs.map(show))));
})();</langsyntaxhighlight>
{{Out}}
<pre>[8,1,6]
Line 2,282 ⟶ 3,634:
Encoding the traditional [[wp:Siamese_method|'Siamese' method]]
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// Number of rows -> n rows of integers
Line 2,448 ⟶ 3,800:
n => unlines(table(" ",
map(xs => map(show, xs), oddMagicTable(n))))));
})();</langsyntaxhighlight>
{{Out}}
<pre>8 1 6
Line 2,470 ⟶ 3,822:
=={{header|jq}}==
'''Adapted from [[#AWK]]'''
<langsyntaxhighlight lang="jq">def odd_magic_square:
if type != "number" or . % 2 == 0 or . <= 0
then error("odd_magic_square requires an odd positive integer")
Line 2,484 ⟶ 3,836:
else [ (($x+$n-1) % $n), (($y+$n+1) % $n), .]
end ) | .[2]
end ;</langsyntaxhighlight>
'''Examples'''
<langsyntaxhighlight lang="jq">def task:
def pp: if length == 0 then empty
else "\(.[0])", (.[1:] | pp )
Line 2,494 ⟶ 3,846:
;
 
(3, 5, 9) | task</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -r -M -c -f odd_magic_square.jq
The magic sum for a square of size 3 is 15:
[8,1,6]
Line 2,516 ⟶ 3,868:
[26,28,39,50,61,72,74,4,15]
[36,38,49,60,71,73,3,14,25]
[37,48,59,70,81,2,13,24,35]</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6.0
 
function magicsquareodd(base::Int)
Line 2,552 ⟶ 3,904:
end
println()
end</langsyntaxhighlight>
 
{{out}}
Line 2,581 ⟶ 3,933:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun f(n: Int, x: Int, y: Int) = (x + y * 2 + 1) % n
Line 2,599 ⟶ 3,951:
}
println("\nThe magic constant is ${(n * n + 1) / 2 * n}")
}</langsyntaxhighlight>
Sample input/output:
{{out}}
<pre>Enter the order of the magic square : 9
<pre>
Enter the order of the magic square : 9
 
2 75 67 59 51 43 35 27 10
Line 2,615 ⟶ 3,966:
72 55 47 39 31 23 15 7 80
 
The magic constant is 369</pre>
</pre>
 
=={{header|Liberty BASIC}}==
<lang lb>
Dim m(1,1)
 
Call magicSquare 5
Call magicSquare 17
 
End
 
Sub magicSquare n
ReDim m(n,n)
inc = 1
count = 1
row = 1
col=(n+1)/2
While count <= n*n
m(row,col) = count
count = count + 1
If inc < n Then
inc = inc + 1
row = row - 1
col = col + 1
If row <> 0 Then
If col > n Then col = 1
Else
row = n
End If
Else
inc = 1
row = row + 1
End If
Wend
Call printSquare n
End Sub
 
Sub printSquare n
'Arbitrary limit to fit width of A4 paper
If n < 23 Then
Print n;" x ";n;" Magic Square --- ";
Print "Magic constant is ";Int((n*n+1)/2*n)
For row = 1 To n
For col = 1 To n
Print Using("####",m(row,col));
Next col
Print
Print
Next row
Else
Notice "Magic Square will not fit on one sheet of paper."
End If
End Sub
</lang>
{{Out}}
<pre>
5 x 5 Magic Square --- Magic constant is 65
17 24 1 8 15
 
23 5 7 14 16
 
4 6 13 20 22
 
10 12 19 21 3
 
11 18 25 2 9
 
17 x 17 Magic Square --- Magic constant is 2465
155 174 193 212 231 250 269 288 1 20 39 58 77 96 115 134 153
 
173 192 211 230 249 268 287 17 19 38 57 76 95 114 133 152 154
 
191 210 229 248 267 286 16 18 37 56 75 94 113 132 151 170 172
 
209 228 247 266 285 15 34 36 55 74 93 112 131 150 169 171 190
 
227 246 265 284 14 33 35 54 73 92 111 130 149 168 187 189 208
 
245 264 283 13 32 51 53 72 91 110 129 148 167 186 188 207 226
 
263 282 12 31 50 52 71 90 109 128 147 166 185 204 206 225 244
 
281 11 30 49 68 70 89 108 127 146 165 184 203 205 224 243 262
 
10 29 48 67 69 88 107 126 145 164 183 202 221 223 242 261 280
 
28 47 66 85 87 106 125 144 163 182 201 220 222 241 260 279 9
 
46 65 84 86 105 124 143 162 181 200 219 238 240 259 278 8 27
 
64 83 102 104 123 142 161 180 199 218 237 239 258 277 7 26 45
 
82 101 103 122 141 160 179 198 217 236 255 257 276 6 25 44 63
 
100 119 121 140 159 178 197 216 235 254 256 275 5 24 43 62 81
 
118 120 139 158 177 196 215 234 253 272 274 4 23 42 61 80 99
 
136 138 157 176 195 214 233 252 271 273 3 22 41 60 79 98 117
 
137 156 175 194 213 232 251 270 289 2 21 40 59 78 97 116 135
</pre>
 
=={{header|Lua}}==
Line 2,723 ⟶ 3,972:
See [[Magic_squares/Lua]].
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Rotate rows and columns of the initial matrix with rows filled in order 1 2 3 .... N^2
 
Method from http://www.jsoftware.com/papers/eem/magicsq.htm
<syntaxhighlight lang="mathematica">rp[v_, pos_] := RotateRight[v, (Length[v] + 1)/2 - pos];
 
<lang Mathematica>
rp[v_, pos_] := RotateRight[v, (Length[v] + 1)/2 - pos];
rho[m_] := MapIndexed[rp, m];
magic[n_] :=
Line 2,735 ⟶ 3,981:
 
square = magic[11] // Grid
Print["Magic number is ", Total[square[[1, 1]]]]</syntaxhighlight>
{{out}}
</lang>
{{out}} (alignment lost in translation to text):
<pre>{68, 80, 92, 104, 116, 7, 19, 31, 43, 55, 56},
 
{68, 80, 92, 104, 116, 7, 19, 31, 43, 55, 56},
{81, 93, 105, 117, 8, 20, 32, 44, 45, 57, 69},
{94, 106, 118, 9, 21, 33, 34, 46, 58, 70, 82},
Line 2,750 ⟶ 3,995:
{53, 65, 77, 78, 90, 102, 114, 5, 17, 29, 41},
{66, 67, 79, 91, 103, 115, 6, 18, 30, 42, 54}
 
Magic number is 671
</pre>
 
Output from code that checks the results
Rows
Line 2,769 ⟶ 4,013:
 
=={{header|Maxima}}==
<langsyntaxhighlight Maximalang="maxima">wrap1(i):= if i>%n% then 1 else if i<1 then %n% else i;
wrap(P):=maplist('wrap1, P);
 
Line 2,785 ⟶ 4,029:
Pc: uprigth(P),
if M[Pc[1],Pc[2]]=0 then P: Pc
else while(M[P[1],P[2]]#0) do P: down(P)));</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="output">(%i6) magic(3);
[ 8 1 6 ]
[ ]
Line 2,820 ⟶ 4,064:
/* magic number for n=7 */
(%i9) lsum(q, q, first(magic(7)));
(%o9) 175</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils
 
proc `^`*magic(base: int, expn: int): int =
varlet (base, exp)length = len(base,$(n exp* n))
result = 1
 
while exp != 0:
if (exp and 1) != 0:
result *= base
exp = exp shr 1
base *= base
 
proc magic(n) =
for row in 1 .. n:
for col in 1 .. n:
let cell = (n * ((row + col - 1 + n div 2) mod n) +
((row + 2 * col - 2) mod n) + 1)
stdout.write align($cell, len).align($(n^2))length)," "' '
echo ""
echo "\nAll sum to magic number ", ((n * n + 1) * n div 2)
for n in [3, 5, 7]:
echo "\nOrder ", n, "\n======="
magic(n)</syntaxhighlight>
 
for n in [5, 3, 7]:
echo "\nOrder ",n,"\n======="
magic(n)</lang>
{{out}}
<pre>Order 53
=======
8 1 6
3 5 7
4 9 2
 
All sum to magic number 15
 
Order 5
=======
17 24 1 8 15
Line 2,858 ⟶ 4,102:
 
All sum to magic number 65
 
Order 3
=======
8 1 6
3 5 7
4 9 2
 
All sum to magic number 15
 
Order 7
Line 2,881 ⟶ 4,117:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: magicSquare(n)
| i j wd |
n sq log asInteger 1+ ->wd
Line 2,892 ⟶ 4,128:
printcr
]
System.Out "Magic constant is : " << n sq 1 + 2 / n * << cr ;</langsyntaxhighlight>
 
{{out}}
Line 2,908 ⟶ 4,144:
{{trans|Perl}}
The index-fiddling differs from Perl since GP vectors start at 1.
<langsyntaxhighlight lang="parigp">magicSquare(n)={
my(M=matrix(n,n),j=n\2+1,i=1);
for(l=1,n^2,
Line 2,921 ⟶ 4,157:
M;
}
magicSquare(7)</langsyntaxhighlight>
{{out}}
<pre>[30 39 48 1 10 19 28]
Line 2,940 ⟶ 4,176:
{{works with|Free Pascal|1.0}}
{{trans|C}}
<langsyntaxhighlight lang="pascal">PROGRAM magic;
(* Magic squares of odd order *)
CONST
Line 2,955 ⟶ 4,191:
END;
WRITELN('The magic number is: ',n*(n*n+1) DIV 2)
END (*magic*).</langsyntaxhighlight>
{{out}}
<pre>
Line 2,973 ⟶ 4,209:
shuffles columns and rows and changed col<-> row to get different looks. n! x n! * 2 different arrangements.
See last column of version before moved to the top row.
<langsyntaxhighlight lang="pascal">PROGRAM magic;
{$IFDEF FPC }{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
Line 3,070 ⟶ 4,306:
Mq := MagicSqrOdd(n,random(2)=0);
writeln(MagicSqrCheck(Mq));
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 3,090 ⟶ 4,326:
 
See [[Magic_squares/Perl|Magic squares/Perl]] for a general magic square generator.
<lang perl></lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function magic_square(integer n)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
if mod(n,2)!=1 or n<1 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: #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;">1</span> <span style="color: #008080;">or</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1</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>
for i=1 to n do
<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 j=1 to n do
<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: #000000;">n</span> <span style="color: #008080;">do</span>
square[i,j] = n*mod(2*i-j+n-1,n) + mod(2*i+j-2,n) + 1
<span style="color: #008080;">for</span> <span style="color: #000000;">j</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;">square</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</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: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">j</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;">n</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">+</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</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=1 to 7 by 2 do
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;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">7</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</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,3,pp_IntCh,false,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 3,147 ⟶ 4,385:
{42,29,23,17,11, 5,48}}
</pre>
 
=={{header|Picat}}==
{{Trans|J}}
 
<syntaxhighlight lang="picat">import util.
 
go =>
foreach(N in [3,5,17])
M=magic_square(N),
print_matrix(M),
check(M),
nl
end,
nl.
 
%
% Not as nice as the J solution.
% But I like the chaining of the functions.
%
magic_square(N) = MS =>
if N mod 2 = 0 then
printf("N (%d) is not odd!\n", N),
halt
end,
R = make_rotate_list(N), % the rotate indices
MS = make_square(N).transpose().rotate_matrix(R).transpose().rotate_matrix(R).
 
%
% make a square matrix of size N (containing the numbers 1..N*N)
%
make_square(N) = [[I*N+J : J in 1..N]: I in 0..N-1].
 
%
% rotate list:
% rotate_list(11) = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
%
make_rotate_list(N) = [I - ceiling(N / 2) : I in 1..N].
 
%
% rotate the matrix M according to rotate list R
%
rotate_matrix(M, R) = [rotate_n(Row,N) : {Row,N} in zip(M,R)].
 
%
% Rotate the list L N steps (either positive or negative N)
% rotate(1..10,3) -> [4,5,6,7,8,9,10,1,2,3]
% rotate(1..10,-3) -> [8,9,10,1,2,3,4,5,6,7]
%
rotate_n(L,N) = Rot =>
Len = L.length,
R = cond(N < 0, Len + N, N),
Rot = [L[I] : I in (R+1..Len) ++ 1..R].
 
%
% Check if M is a magic square
%
check(M) =>
N = M.length,
Sum = N*(N*N+1) // 2, % The correct sum.
println(sum=Sum),
Rows = [sum(Row) : Row in M],
Cols = [sum(Col) : Col in M.transpose()],
Diag1 = sum([M[I,I] : I in 1..N]),
Diag2 = sum([M[I,N-I+1] : I in 1..N]),
All = Rows ++ Cols ++ [Diag1, Diag2],
OK = true,
foreach(X in All)
if X != Sum then
printf("%d != %d\n", X, Sum),
OK := false
end
end,
if OK then
println(ok)
else
println(not_ok)
end,
nl.
 
% Print the matrix
print_matrix(M) =>
N = M.len,
printf("N=%d\n",N),
Format = to_fstring("%%%dd",max(flatten(M)).to_string().length+1),
foreach(Row in M)
foreach(X in Row)
printf(Format, X)
end,
nl
end,
nl.</syntaxhighlight>
 
{{out}}
<pre>N=3
6 7 2
1 5 9
8 3 4
 
sum = 15
ok
 
 
N=5
9 15 16 22 3
20 21 2 8 14
1 7 13 19 25
12 18 24 5 6
23 4 10 11 17
 
sum = 65
ok
 
N=17
27 45 63 81 99 117 135 153 154 172 190 208 226 244 262 280 9
62 80 98 116 134 152 170 171 189 207 225 243 261 279 8 26 44
97 115 133 151 169 187 188 206 224 242 260 278 7 25 43 61 79
132 150 168 186 204 205 223 241 259 277 6 24 42 60 78 96 114
167 185 203 221 222 240 258 276 5 23 41 59 77 95 113 131 149
202 220 238 239 257 275 4 22 40 58 76 94 112 130 148 166 184
237 255 256 274 3 21 39 57 75 93 111 129 147 165 183 201 219
272 273 2 20 38 56 74 92 110 128 146 164 182 200 218 236 254
1 19 37 55 73 91 109 127 145 163 181 199 217 235 253 271 289
36 54 72 90 108 126 144 162 180 198 216 234 252 270 288 17 18
71 89 107 125 143 161 179 197 215 233 251 269 287 16 34 35 53
106 124 142 160 178 196 214 232 250 268 286 15 33 51 52 70 88
141 159 177 195 213 231 249 267 285 14 32 50 68 69 87 105 123
176 194 212 230 248 266 284 13 31 49 67 85 86 104 122 140 158
211 229 247 265 283 12 30 48 66 84 102 103 121 139 157 175 193
246 264 282 11 29 47 65 83 101 119 120 138 156 174 192 210 228
281 10 28 46 64 82 100 118 136 137 155 173 191 209 227 245 263
 
sum = 2465
ok</pre>
 
===Testing a larger instance===
<syntaxhighlight lang="picat">go2 =>
N = 313,
M = magic_square(N),
check(M),
nl.</syntaxhighlight>
 
{{out}}
<pre>sum = 15332305
ok</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
(de magic (A)
(let
Line 3,177 ⟶ 4,559:
(magic 5)
(prinl)
(magic 7)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,198 ⟶ 4,580:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">magic: procedure options (main); /* 18 April 2014 */
declare n fixed binary;
 
Line 3,235 ⟶ 4,617:
put skip list ('The magic number is' || sum(m(1,*)));
end;
end magic;</langsyntaxhighlight>
{{out}}
<pre>What is the order of the magic square?
Line 3,257 ⟶ 4,639:
20 11 2 49 40 31 22
The magic number is 175</pre>
 
=={{header|PureBasic}}==
{{trans|Pascal}}
<lang purebasic>#N=9
Define.i i,j
 
If OpenConsole("Magic squares")
PrintN("The square order is: "+Str(#N))
For i=1 To #N
For j=1 To #N
Print(RSet(Str((i*2-j+#N-1) % #N*#N + (i*2+j-2) % #N+1),5))
Next
PrintN("")
Next
PrintN("The magic number is: "+Str(#N*(#N*#N+1)/2))
EndIf
Input()</lang>
{{out}}
<pre>
The square order is: 9
2 75 67 59 51 43 35 27 10
22 14 6 79 71 63 46 38 30
42 34 26 18 1 74 66 58 50
62 54 37 29 21 13 5 78 70
73 65 57 49 41 33 25 17 9
12 4 77 69 61 53 45 28 20
32 24 16 8 81 64 56 48 40
52 44 36 19 11 3 76 68 60
72 55 47 39 31 23 15 7 80
The magic number is: 369
</pre>
 
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">>>> def magic(n):
for row in range(1, n + 1):
print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
Line 3,335 ⟶ 4,686:
 
All sum to magic number 175
>>> </langsyntaxhighlight>
 
===Composition of pure functions===
Line 3,341 ⟶ 4,692:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Magic squares of odd order N'''
 
from itertools import cycle, islice, repeat
Line 3,528 ⟶ 4,879:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Magic squares of odd order N:
Line 3,554 ⟶ 4,905:
 
=={{header|R}}==
 
See [http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order#R here] for the solution for all three cases.
 
Line 3,568 ⟶ 4,918:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
;; Using "helpful formulae" in:
;; http://en.wikipedia.org/wiki/Magic_square#Method_for_constructing_a_magic_square_of_odd_order
Line 3,600 ⟶ 4,950:
(displayln (show-magic-square 3))
(displayln (show-magic-square 5))
(displayln (show-magic-square 9))</langsyntaxhighlight>
{{out}}
<pre>MAGIC SQUARE ORDER:3
Line 3,667 ⟶ 5,017:
=={{header|REXX}}==
This REXX version will also generate a square of an even order, but it'll not be a ''magic square''.
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays magic squares (odd N will be a true magic square).*/
parse arg N . /*obtain the optional argument from CL.*/
if N=='' | N=="," then N=5 /*Not specified? Then use the default.*/
Line 3,689 ⟶ 5,039:
say /* [↓] If an odd square, show magic #.*/
if N//2 then say 'The magic number (or magic constant is): ' N * (NN+1) % 2
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input of: &nbsp; '''5'''}}
<pre>
Line 3,734 ⟶ 5,084:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
n=9
see "the square order is : " + n + nl
Line 3,744 ⟶ 5,094:
see nl
next
see "'the magic number is : " + n*(n*n+1) / 2 + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,761 ⟶ 5,111:
 
the magic number is : 369
</pre>
 
=={{header|RPL}}==
{{trans|IS-BASIC}}
≪ → n
≪ n DUP 2 →LIST 0 CON
1 n '''FOR''' j
1 n '''FOR''' k
j k 2 →LIST
j 2 * k - n + 1 - n MOD n *
j 2 * k + 2 - n MOD 1 +
+ PUT
'''NEXT NEXT'''
n DUP SQ 1 + * 2 /
≫ ≫ '<span style="color:blue">ODDMAGIC</span>' STO
 
5 <span style="color:blue">ODDMAGIC</span>
{{out}}
<pre>
2: [[2 23 19 15 6]
[14 10 1 22 18]
[21 17 13 9 5]
[8 4 25 16 12]
[20 11 7 3 24]]
1: 65
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def odd_magic_square(n)
raise ArgumentError "Need odd positive number" if n.even? || n <= 0
n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} }
Line 3,774 ⟶ 5,149:
odd_magic_square(n).each{|row| puts fmt % row}
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,802 ⟶ 5,177:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
let n = 9;
let mut square = vec![vec![0; n]; n];
Line 3,814 ⟶ 5,189:
let sum = n * (((n * n) + 1) / 2);
println!("The sum of the square is {}.", sum);
}</langsyntaxhighlight>
 
{{out}}
Line 3,829 ⟶ 5,204:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala"> def magicSquare( n:Int ) : Option[Array[Array[Int]]] = {
require(n % 2 != 0, "n must be an odd number")
 
Line 3,888 ⟶ 5,263:
 
printMagicSquare(7)
}</langsyntaxhighlight>
 
{{out}}
Line 3,908 ⟶ 5,283:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: succ (in integer: num, in integer: max) is
Line 3,944 ⟶ 5,319:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,960 ⟶ 5,335:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func magic_square(n {.is_pos && .is_odd}) {
var i = 0
var j = intidiv(n/, 2)
 
var magic_square = []
Line 3,987 ⟶ 5,362:
}
 
var(n=5) = ARGV»to_i»()»...
var sq = magic_square(n)
print_square(sq)
 
say "\nThe magic number is: #{sq[0].sum}"</langsyntaxhighlight>
 
{{out}}
Line 4,019 ⟶ 5,394:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift 5">extension String: Error {}
 
struct Point: CustomStringConvertible {
Line 4,177 ⟶ 5,552:
try MagicSquare(base: 7).createOdd()
 
</syntaxhighlight>
</lang>
Demonstrating:
{{works with|Swift 5}}
Line 4,216 ⟶ 5,591:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc magicSquare {order} {
if {!($order & 1) || $order < 0} {
error "order must be odd and positive"
Line 4,233 ⟶ 5,608:
}
return $s
}</langsyntaxhighlight>
Demonstrating:
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
set square [magicSquare 5]
puts [join [lmap row $square {join [lmap n $row {format "%2s" $n}]}] "\n"]
puts "magic number = [tcl::mathop::+ {*}[lindex $square 0]]"</langsyntaxhighlight>
{{out}}
<pre>
Line 4,251 ⟶ 5,626:
</pre>
 
==={{header|TI-83 BASIC}}===
{{trans|C}}
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}}
<langsyntaxhighlight lang="ti83b">9→N
DelVar [A]:{N,N}→dim([A])
For(I,1,N)
Line 4,261 ⟶ 5,636:
End
End
[A]</langsyntaxhighlight>
{{out}}
<pre>
Line 4,274 ⟶ 5,649:
[72 55 47 39 31 23 15 7 80]]
</pre>
 
=={{header|uBasic/4tH}}==
{{trans|FreeBASIC}}
<lang>' ------=< MAIN >=------
Proc _magicsq(5)
Proc _magicsq(11)
End
 
_magicsq Param (1) Local (4)
 
' reset the array
For b@ = 0 to 255
@(b@) = 0
Next
 
If ((a@ % 2) = 0) + (a@ < 3) + (a@ > 15) Then
Print "error: size is not odd or size is smaller then 3 or bigger than 15"
Return
EndIf
 
' start in the middle of the first row
b@ = 1
c@ = a@ - (a@ / 2)
d@ = 1
e@ = a@ * a@
 
' main loop for creating magic square
Do
If @(c@*a@+d@) = 0 Then
@(c@*a@+d@) = b@
If (b@ % a@) = 0 Then
d@ = d@ + 1
Else
c@ = c@ + 1
d@ = d@ - 1
EndIf
b@ = b@ + 1
EndIf
If c@ > a@ Then
c@ = 1
Do While @(c@*a@+d@) # 0
c@ = c@ + 1
Loop
EndIf
If d@ < 1 Then
d@ = a@
Do While @(c@*a@+d@) # 0
d@ = d@ - 1
Loop
EndIf
Until b@ > e@
Loop
 
Print "Odd magic square size: "; a@; " * "; a@
Print "The magic sum = "; ((e@+1) / 2) * a@
Print
 
For d@ = 1 To a@
For c@ = 1 To a@
Print Using "____"; @(c@*a@+d@);
Next
Print
Next
Print
Return
</lang>
{{out}}
<pre>Odd magic square size: 5 * 5
The magic sum = 65
 
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
 
Odd magic square size: 11 * 11
The magic sum = 671
 
68 81 94 107 120 1 14 27 40 53 66
80 93 106 119 11 13 26 39 52 65 67
92 105 118 10 12 25 38 51 64 77 79
104 117 9 22 24 37 50 63 76 78 91
116 8 21 23 36 49 62 75 88 90 103
7 20 33 35 48 61 74 87 89 102 115
19 32 34 47 60 73 86 99 101 114 6
31 44 46 59 72 85 98 100 113 5 18
43 45 58 71 84 97 110 112 4 17 30
55 57 70 83 96 109 111 3 16 29 42
56 69 82 95 108 121 2 15 28 41 54
 
 
0 OK, 0:64
</pre>
 
=={{header|VBA}}==
{{trans|C}}
Works with Excel VBA.
<lang vb>Sub magicsquare()
'Magic squares of odd order
Const n = 9
Dim i As Integer, j As Integer, v As Integer
Debug.Print "The square order is: " & n
For i = 1 To n
For j = 1 To n
Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Next j
Next i
Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2
End Sub 'magicsquare
</lang>
 
=={{header|VBScript}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Sub magic_square(n)
Dim ms()
Line 4,428 ⟶ 5,691:
End Sub
 
magic_square(5)</syntaxhighlight>
</lang>
 
{{Out}}
<pre>17 24 1 8 15
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9</pre>
</pre>
 
=={{header|Visual BasicVTL-2}}==
{{trans|C}}
<syntaxhighlight lang="vtl2">10 N=1
{{works with|Visual Basic|VB6 Standard}}
20 ?="Magic square of order ";
<lang vb>Sub magicsquare()
30 ?=N
'Magic squares of odd order
40 ?=" with constant ";
Const n = 9
50 ?=N*N+1/2*N
Dim i As Integer, j As Integer, v As Integer
60 ?=":"
Debug.Print "The square order is: " & n
70 Y=0
For i = 1 To n
80 X=0
For j = 1 To n
90 ?=Y*2+N-X/N*0+%*N+(Y*2+X+1/N*0+%+1
v = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
100 $=9
Debug.Print Right(Space(5) & v, 5);
110 X=X+1
Next j
120 #=X<N*90
Debug.Print
130 ?=""
Next i
140 Y=Y+1
Debug.Print "The magic number is: " & n * (n * n + 1) \ 2
150 #=Y<N*80
End Sub 'magicsquare
160 ?=""
</lang>
170 N=N+2
180 #=7>N*20</syntaxhighlight>
{{out}}
<pre>Magic square of order 1 with constant 1:
<pre>
1
The square order is: 9
 
2 75 67 59 51 43 35 27 10
Magic square of order 3 with constant 15:
22 14 6 79 71 63 46 38 30
2 42 34 9 26 18 1 74 66 58 504
7 62 54 5 37 29 21 13 5 78 703
6 73 65 1 57 49 41 33 25 17 98
 
12 4 77 69 61 53 45 28 20
Magic square of order 5 with constant 65:
32 24 16 8 81 64 56 48 40
2 52 44 23 36 19 11 3 7615 68 606
14 72 5510 47 391 31 23 22 15 7 8018
21 17 13 9 5
The magic number is: 369
8 4 25 16 12
</pre>
20 11 7 3 24
 
Magic square of order 7 with constant 175:
2 45 39 33 27 21 8
18 12 6 49 36 30 24
34 28 15 9 3 46 40
43 37 31 25 19 13 7
10 4 47 41 35 22 16
26 20 14 1 44 38 32
42 29 23 17 11 5 48</pre>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var ms = Fn.new { |n|
var M = Fn.new { |x| (x + n - 1) % n }
if (n <= 0 || n&1 == 0) {
n = 5
System.print("forcing size %(n)")
}
var m = List.filled(n * n, 0)
var i = 0
var j = (n/2).floor
for (k in 1..n*n) {
m[i*n + j] = k
if (m[M.call(i)*n + M.call(j)] != 0) {
i = (i + 1) % n
} else {
i = M.call(i)
j = M.call(j)
}
}
return [n, m]
}
 
var res = ms.call(5)
var n = res[0]
var m = res[1]
for (i in 0...n) {
for (j in 0...n) Fmt.write("$4d", m[i*n+j])
System.print()
}
System.print("\nMagic number : %(((n*n + 1)/2).floor * n)")</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2011}}
<lang vbnet>Sub magicsquare()
'Magic squares of odd order
Const n = 9
Dim i, j, v As Integer
Console.WriteLine("The square order is: " & n)
For i = 1 To n
For j = 1 To n
v = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Console.Write(" " & Right(Space(5) & v, 5))
Next j
Console.WriteLine("")
Next i
Console.WriteLine("The magic number is: " & n * (n * n + 1) \ 2)
End Sub 'magicsquare</lang>
{{out}}
<pre>
15 8 1 24 17
The square order is: 9
16 214 757 675 59 51 43 35 27 1023
22 20 14 13 6 79 71 63 46 38 304
423 21 34 19 2612 18 1 74 66 58 5010
629 542 25 37 18 29 21 13 5 78 7011
 
73 65 57 49 41 33 25 17 9
Magic number : 65
12 4 77 69 61 53 45 28 20
32 24 16 8 81 64 56 48 40
52 44 36 19 11 3 76 68 60
72 55 47 39 31 23 15 7 80
The magic number is: 369
</pre>
 
=={{header|XPL0}}==
{{trans|ALGOL W}}
<syntaxhighlight lang "XPL0"> \Construct a magic square of odd order - as a procedure can't return an
\ array, the caller must supply one that is big enough.
function MagicSquare( Square, Order );
integer Square, Order;
integer Row, Col, I, J;
 
\Ensure a row/col position is on the square
function InSquare; int Pos ;
return if Pos < 1 then Order else if Pos > Order then 1 else Pos;
 
\move "up" a row in the square
function Up; int Row; return InSquare( Row - 1 );
 
\move "across right" in the square
function Right; int Col ; return InSquare( Col + 1 );
 
if (Order&1) = 0 or Order < 1 then begin
\can't make a magic square of the specified order
return false
end
else begin
\Order is OK - construct the square using de la Loubere's
\ algorithm as in the Wikipedia page
 
\initialise square
for I := 1 to Order do for J := 1 to Order do Square( I, J ) := 0;
 
\initial position is the middle of the top row
Col := ( Order + 1 ) / 2;
Row := 1;
\construct square
for I := 1 to ( Order * Order ) do begin
Square( Row, Col ) := I;
if Square( Up( Row ), Right( Col ) ) # 0 then begin
\the up/right position is already taken, move down
Row := Row + 1;
end
else begin
\can move up/right
Row := Up( Row );
Col := Right( Col );
end
end; \for_i
\sucessful result
return true
end; \magicSquare
 
\prints the magic square
procedure PrintSquare( Square, Order );
integer Square, Order;
integer Sum, W, I_W, I, J;
begin
\set integer width to accomodate the largest number in the square
W := ( Order * Order ) / 10;
I_W := 1;
while W > 0 do begin I_W := I_W + 1; W := W / 10 end;
Format(I_W+1, 0);
Sum:= 0;
for I := 1 to Order do Sum := Sum + Square( 1, I );
Text(0, "maqic square of order "); IntOut(0, Order);
Text(0, " : Sum: "); IntOut(0, Sum );
for I := 1 to Order do begin
CrLf(0);
RlOut(0, float(Square( I, 1 )) );
for J := 2 to Order do RlOut(0, float(Square( I, J )) )
end; \for_I
CrLf(0);
end; \printSquare
 
\test the magic square generation
integer Sq ( 1+11, 1+11 ), L, I;
begin
L:= [1, 3, 5, 7];
for I := 0 to 3 do begin
if MagicSquare( Sq, L(I) ) then PrintSquare( Sq, L(I) )
else Text(0, "can't generate square^m^j" );
end \for_I
end]</syntaxhighlight>
{{out}}
<pre>maqic square of order 1 : Sum: 1
1
maqic square of order 3 : Sum: 15
8 1 6
3 5 7
4 9 2
maqic square of order 5 : Sum: 65
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
maqic square of order 7 : Sum: 175
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20</pre>
 
=={{header|zkl}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="zkl">fcn rmod(n,m){ n=n%m; if (n<0) n+=m; n } // Ruby: -5%3-->1
fcn odd_magic_square(n){ //-->list of n*n numbers, row order
if (n.isEven or n <= 0) throw(Exception.ValueError("Need odd positive number"));
Line 4,516 ⟶ 5,904:
fmt := "%%%dd".fmt((n*n).toString().len() + 1) * n;
odd_magic_square(n).pump(Console.println,T(Void.Read,n-1),fmt.fmt);
});</langsyntaxhighlight>
{{out}}
<pre>Size 3, magic sum 15
<pre>
Size 3, magic sum 15
8 1 6
3 5 7
Line 4,540 ⟶ 5,927:
20 31 42 53 55 66 77 7 18
30 41 52 63 65 76 6 17 19
40 51 62 64 75 5 16 27 29</pre>
</pre>
1,983

edits