Magic squares of odd order: Difference between revisions

m
syntax highlighting fixup automation
(Add BQN)
m (syntax highlighting fixup automation)
Line 38:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F magic(n)
L(row) 1..n
print(((1..n).map(col -> @n * ((@row + col - 1 + @n I/ 2) % @n)
Line 46:
L(n) (5, 3, 7)
print("\nOrder #.\n=======".format(n))
magic(n)</langsyntaxhighlight>
 
{{out}}
Line 83:
=={{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 124:
PG DC CL92' ' buffer
YREGS
END MAGICS</langsyntaxhighlight>
{{out}}
<pre>
Line 139:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Command_Line;
 
procedure Magic_Square is
Line 173:
Ada.Text_IO.New_Line;
end loop;
end Magic_Square;</langsyntaxhighlight>
 
{{out}}
Line 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 253:
 
# test the magic square generation #
FOR order BY 2 TO 7 DO print square( magic square( order ) ) OD</langsyntaxhighlight>
{{out}}
<pre>
Line 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 355:
end for_i
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 383:
{{works with|Dyalog APL}}
{{trans|C}}
<langsyntaxhighlight APLlang="apl">magic←{⍵{+/1,(1 ⍺⍺)×⍺(⍺⍺|1+⊢+2×⊣)⍵,⍺⍺-⍵+1}/¨⎕IO-⍨⍳⍵ ⍵}</langsyntaxhighlight>
{{out}}
<pre> magic¨ 1 3 5 7
Line 400:
to allow for first class functions and closures.
 
<langsyntaxhighlight AppleScriptlang="applescript">---------------- MAGIC SQUARE OF ODD ORDER ---------------
 
-- oddMagicSquare :: Int -> [[Int]]
Line 576:
g
end if
end cond</langsyntaxhighlight>
{{Out}}
magic(3)
Line 633:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">oddMagicSquare: function [n][
ensure -> and? odd? n
n >= 0
Line 654:
]
print ""
]</langsyntaxhighlight>
 
{{out}}
Line 683:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">
msgbox % OddMagicSquare(5)
msgbox % OddMagicSquare(7)
Line 723:
return str
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 745:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MAGIC_SQUARES_OF_ODD_ORDER.AWK
BEGIN {
Line 816:
printf("\t: %d diagonal bottom left to top right\n",total)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 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 868:
260 NEXT I
270 PRINT "MAGIC CONSTANT: ";N * (N * N + 1) / 2
</syntaxhighlight>
</lang>
{{out}}
<pre>ENTER N: 5
Line 879:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "MagicN.bas"
110 DO
120 INPUT PROMPT "The square order: ":N
Line 889:
180 PRINT
190 NEXT
200 PRINT "The magic number is:";N*(N^2+1)/2</langsyntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
rem Magic squares of odd order
setlocal EnableDelayedExpansion
Line 910:
set /a w=n*(n*n+1)/2
echo The magic number is: %w%
pause</langsyntaxhighlight>
{{out}}
<pre>The square order is: 9
Line 927:
=={{header|bc}}==
{{works with|GNU bc}}
<langsyntaxhighlight lang="bc">define magic_constant(n) {
return(((n * n + 1) / 2) * n)
}
Line 955:
}
 
temp = print_magic_square(5)</langsyntaxhighlight>
 
{{Out}}
Line 967:
=={{header|BCPL}}==
{{trans|C}}
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let cell(n, x, y) = f(n, n-x-1, y)*n + f(n, x, y) + 1
Line 981:
$)
 
let start() be for n = 1 to 7 by 2 do magic(n)</langsyntaxhighlight>
{{out}}
<pre>Magic square of order 1 with constant 1:
Line 1,010:
{{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 1,022:
=={{header|BQN}}==
{{trans|C}}
<langsyntaxhighlight BQNlang="bqn">Magic ← {𝕏{+´1∾1‿𝕗×𝕨(𝕗|1+⊢+2×⊣)𝕩∾𝕗-𝕩+1}´¨↕2⥊𝕩}
Magic¨ ⟨1,3,5,7⟩</langsyntaxhighlight>
{{out}}
<pre>┌─
Line 1,039:
=={{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 1,066:
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>$ ./magic 5
Line 1,078:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <sstream>
Line 1,157:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,173:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">magic_square = cluster is create, unparse, magic_number
rep = array[array[int]]
 
Line 1,241:
print_magic_square(n)
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>Magic square of order 1 with magic number 1:
Line 1,268:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun magic-square (n)
(loop for i from 1 to n
collect
Line 1,288:
(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,301:
=={{header|Cowgol}}==
{{trans|C}}
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub magic(n: uint16) is
Line 1,339:
magic(n);
n := n + 2;
end loop;</langsyntaxhighlight>
{{out}}
<pre>Magic square of order 1 with constant 1:
Line 1,366:
=={{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,389:
 
writeln("\nMagic constant: ", ((n * n + 1) * n) / 2);
}}</langsyntaxhighlight>
{{out}}
<pre>17 24 1 8 15
Line 1,401:
===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,466:
stderr.writefln("Requires n odd and larger than 0.");
return 1;
}</langsyntaxhighlight>
{{out}}
<pre>15 8 1 24 17
Line 1,480:
 
=={{header|Draco}}==
<langsyntaxhighlight 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
 
Line 1,550:
print_magic_square(sq5);
print_magic_square(sq7)
corp</langsyntaxhighlight>
{{out}}
<pre>Magic square of order 1 with magic number 1:
Line 1,578:
=={{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,611:
(array-print ms))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,660:
=={{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,677:
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,708:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MAGIC_SQUARE
 
Line 1,802:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
Same as FreeBasic version
Line 1,822:
=={{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,839:
"Magic number: %d\n\n" printf ;
 
3 5 11 [ show-square ] tri@</langsyntaxhighlight>
{{out}}
<pre>
Line 1,873:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program Magic_Square
implicit none
 
Line 1,902:
f2 = n * (1 + n * n) / 2
end function
end program</langsyntaxhighlight>
Output:
<pre>Magic Square Order: 15
Line 1,924:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight FreeBASIClang="freebasic">' version 23-06-2015
' compile with: fbc -s console
 
Line 2,017:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Odd magic square size: 5 * 5 Odd magic square size: 11 * 11
Line 2,036:
=={{header|Frink}}==
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."
<langsyntaxhighlight lang="frink">order = length[ARGS] > 0 ? eval[ARGS@0] : undef
until isInteger[order] and order mod 2 == 1
order = eval[input["Enter order (must be odd): ", 3]]
Line 2,059:
 
println[formatTable[a]]
println["Magic number is " + sum[a@0]]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,072:
=={{header|Go}}==
{{trans|C}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,111:
fmt.Println()
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,123:
====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 2,184:
putStr " = "
putStrLn $ show $ magicSum x
putStrLn $ display $ magicNumber x</langsyntaxhighlight>
 
====Transpose . cycled====
Line 2,190:
Defining the magic square as two applications of ('''transpose . cycled''') to a simply ordered square.
 
<langsyntaxhighlight Haskelllang="haskell">import Control.Monad (join)
import Data.List (maximumBy, transpose)
import Data.List.Split (chunksOf)
Line 2,237:
<*> succ . maximum . fmap length . join
)
$ fmap show <$> rows</langsyntaxhighlight>
{{Out}}
<pre> 8 1 6
Line 2,260:
Encoding the traditional [[wp:Siamese_method|'Siamese' method]]
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE TupleSections #-}
 
import Control.Monad (forM_)
Line 2,352:
putStrLn $ unlines (table " " (fmap show <$> test))
print $ checked test
putStrLn ""</langsyntaxhighlight>
{{Out}}
<pre>8 1 6
Line 2,381:
 
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 2,405:
s := *(n*n)+2
every r := !sq do every writes(right(!r,s)|"\n")
end</langsyntaxhighlight>
 
{{out}}
Line 2,423:
Based on http://www.jsoftware.com/papers/eem/magicsq.htm
 
<langsyntaxhighlight Jlang="j">ms=: i:@<.@-: |."_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 2,439:
Example use:
 
<langsyntaxhighlight Jlang="j"> ms 5
9 15 16 22 3
20 21 2 8 14
Line 2,448:
65
~.+/ms 101
515201</langsyntaxhighlight>
 
Note also that an important feature of magic squares is that their diagonals sum the same way:
Line 2,458:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class MagicSquare {
 
public static void main(String[] args) {
Line 2,504:
return grid;
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,521:
( and referring to http://www.jsoftware.com/papers/eem/magicsq.htm )
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// n -> [[n]]
Line 2,606:
}
).join('\n\n')
})();</langsyntaxhighlight>
 
Output:
Line 2,668:
 
(2nd Haskell version: ''cycledRows . transpose . cycledRows'')
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// magicSquare :: Int -> [[Int]]
Line 2,740:
.map(magicSquare)
.map(xs => unlines(xs.map(show))));
})();</langsyntaxhighlight>
{{Out}}
<pre>[8,1,6]
Line 2,763:
Encoding the traditional [[wp:Siamese_method|'Siamese' method]]
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// Number of rows -> n rows of integers
Line 2,929:
n => unlines(table(" ",
map(xs => map(show, xs), oddMagicTable(n))))));
})();</langsyntaxhighlight>
{{Out}}
<pre>8 1 6
Line 2,951:
=={{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,965:
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,975:
;
 
(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,997:
[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 3,033:
end
println()
end</langsyntaxhighlight>
 
{{out}}
Line 3,062:
=={{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 3,080:
}
println("\nThe magic constant is ${(n * n + 1) / 2 * n}")
}</langsyntaxhighlight>
Sample input/output:
{{out}}
Line 3,100:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
Dim m(1,1)
 
Line 3,150:
End If
End Sub
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,207:
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
<langsyntaxhighlight Mathematicalang="mathematica">rp[v_, pos_] := RotateRight[v, (Length[v] + 1)/2 - pos];
rho[m_] := MapIndexed[rp, m];
magic[n_] :=
Line 3,213:
 
square = magic[11] // Grid
Print["Magic number is ", Total[square[[1, 1]]]]</langsyntaxhighlight>
{{out}}
(alignment lost in translation to text):
Line 3,245:
 
=={{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 3,261:
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 3,296:
/* 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(n: int) =
Line 3,314:
for n in [3, 5, 7]:
echo "\nOrder ", n, "\n======="
magic(n)</langsyntaxhighlight>
 
{{out}}
Line 3,349:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: magicSquare(n)
| i j wd |
n sq log asInteger 1+ ->wd
Line 3,360:
printcr
]
System.Out "Magic constant is : " << n sq 1 + 2 / n * << cr ;</langsyntaxhighlight>
 
{{out}}
Line 3,376:
{{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 3,389:
M;
}
magicSquare(7)</langsyntaxhighlight>
{{out}}
<pre>[30 39 48 1 10 19 28]
Line 3,408:
{{works with|Free Pascal|1.0}}
{{trans|C}}
<langsyntaxhighlight lang="pascal">PROGRAM magic;
(* Magic squares of odd order *)
CONST
Line 3,423:
END;
WRITELN('The magic number is: ',n*(n*n+1) DIV 2)
END (*magic*).</langsyntaxhighlight>
{{out}}
<pre>
Line 3,441:
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,538:
Mq := MagicSqrOdd(n,random(2)=0);
writeln(MagicSqrCheck(Mq));
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 3,558:
 
See [[Magic_squares/Perl|Magic squares/Perl]] for a general magic square generator.
<syntaxhighlight lang ="perl"></langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">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>
Line 3,594:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,622:
{{Trans|J}}
 
<langsyntaxhighlight Picatlang="picat">import util.
 
go =>
Line 3,708:
nl
end,
nl.</langsyntaxhighlight>
 
{{out}}
Line 3,753:
 
===Testing a larger instance===
<langsyntaxhighlight Picatlang="picat">go2 =>
N = 313,
M = magic_square(N),
check(M),
nl.</langsyntaxhighlight>
 
{{out}}
Line 3,764:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
(de magic (A)
(let
Line 3,792:
(magic 5)
(prinl)
(magic 7)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,813:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">magic: procedure options (main); /* 18 April 2014 */
declare n fixed binary;
 
Line 3,850:
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,875:
=={{header|PureBasic}}==
{{trans|Pascal}}
<langsyntaxhighlight lang="purebasic">#N=9
Define.i i,j
 
Line 3,888:
PrintN("The magic number is: "+Str(#N*(#N*#N+1)/2))
EndIf
Input()</langsyntaxhighlight>
{{out}}
<pre>
Line 3,906:
=={{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,950:
 
All sum to magic number 175
>>> </langsyntaxhighlight>
 
===Composition of pure functions===
Line 3,956:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Magic squares of odd order N'''
 
from itertools import cycle, islice, repeat
Line 4,143:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Magic squares of odd order N:
Line 4,169:
 
=={{header|QB64}}==
<langsyntaxhighlight lang="qb64">_Title "Magic Squares of Odd Order"
'$Dynamic
DefLng A-Z
Line 4,223:
Next row
End If
End Sub</langsyntaxhighlight>
{{Out}}
<pre>Order 5 Magic Square constant is 65
Line 4,264:
 
=={{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 4,296:
(displayln (show-magic-square 3))
(displayln (show-magic-square 5))
(displayln (show-magic-square 9))</langsyntaxhighlight>
{{out}}
<pre>MAGIC SQUARE ORDER:3
Line 4,363:
=={{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 4,385:
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 4,430:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
n=9
see "the square order is : " + n + nl
Line 4,441:
next
see "the magic number is : " + n*(n*n+1) / 2 + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,460:
 
=={{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 4,470:
odd_magic_square(n).each{|row| puts fmt % row}
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,498:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
let n = 9;
let mut square = vec![vec![0; n]; n];
Line 4,510:
let sum = n * (((n * n) + 1) / 2);
println!("The sum of the square is {}.", sum);
}</langsyntaxhighlight>
 
{{out}}
Line 4,525:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala"> def magicSquare( n:Int ) : Option[Array[Array[Int]]] = {
require(n % 2 != 0, "n must be an odd number")
 
Line 4,584:
 
printMagicSquare(7)
}</langsyntaxhighlight>
 
{{out}}
Line 4,604:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: succ (in integer: num, in integer: max) is
Line 4,640:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,656:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func magic_square(n {.is_pos && .is_odd}) {
var i = 0
var j = int(n/2)
Line 4,687:
print_square(sq)
 
say "\nThe magic number is: #{sq[0].sum}"</langsyntaxhighlight>
 
{{out}}
Line 4,715:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift 5">extension String: Error {}
 
struct Point: CustomStringConvertible {
Line 4,873:
try MagicSquare(base: 7).createOdd()
 
</syntaxhighlight>
</lang>
Demonstrating:
{{works with|Swift 5}}
Line 4,912:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc magicSquare {order} {
if {!($order & 1) || $order < 0} {
error "order must be odd and positive"
Line 4,929:
}
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,950:
{{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,957:
End
End
[A]</langsyntaxhighlight>
{{out}}
<pre>
Line 4,973:
=={{header|uBasic/4tH}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="text">' ------=< MAIN >=------
Proc _magicsq(5)
Line 5,036:
Print
Return
</syntaxhighlight>
</lang>
{{out}}
<pre>Odd magic square size: 5 * 5
Line 5,069:
{{trans|C}}
Works with Excel VBA.
<langsyntaxhighlight lang="vb">Sub magicsquare()
'Magic squares of odd order
Const n = 9
Line 5,081:
Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2
End Sub 'magicsquare
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Sub magic_square(n)
Dim ms()
Line 5,125:
 
magic_square(5)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 5,139:
{{trans|C}}
{{works with|Visual Basic|VB6 Standard}}
<langsyntaxhighlight lang="vb">Sub magicsquare()
'Magic squares of odd order
Const n = 9
Line 5,153:
Debug.Print "The magic number is: " & n * (n * n + 1) \ 2
End Sub 'magicsquare
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,171:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2011}}
<langsyntaxhighlight lang="vbnet">Sub magicsquare()
'Magic squares of odd order
Const n = 9
Line 5,184:
Next i
Console.WriteLine("The magic number is: " & n * (n * n + 1) \ 2)
End Sub 'magicsquare</langsyntaxhighlight>
{{out}}
<pre>
Line 5,202:
=={{header|VTL-2}}==
{{trans|C}}
<langsyntaxhighlight VTL2lang="vtl2">10 N=1
20 ?="Magic square of order ";
30 ?=N
Line 5,219:
160 ?=""
170 N=N+2
180 #=7>N*20</langsyntaxhighlight>
{{out}}
<pre>Magic square of order 1 with constant 1:
Line 5,248:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var ms = Fn.new { |n|
Line 5,278:
System.print()
}
System.print("\nMagic number : %(((n*n + 1)/2).floor * n)")</langsyntaxhighlight>
 
{{out}}
Line 5,293:
=={{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 5,303:
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>
10,333

edits