A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant).

The numbers are usually (but not always) the first   N2   positive integers.

A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.



 8 
 1 
 6


 3 
 5 
 7


 4 
 9 
 2



Task
For any odd   N,   generate a magic square with the integers    1 ──► N,   and show the results here.

Optionally, show the magic number.

You should demonstrate the generator by showing at least a magic square for   N = 5.



 Related tasks
 Magic squares of singly even order
 Magic squares of doubly even order



 See also

 MathWorld™ entry: Magic_square 
 Odd Magic Squares (1728.org)


void main(in string[] args)
{
    import std.stdio, std.conv, std.range, std.algorithm, std.exception;
 
    immutable n = args.length == 2 ? args[1].to!uint : 5;
    enforce(n > 0 && n % 2 == 1, "Only odd n > 1");
    immutable len = text(n ^^ 2).length.text;
   // writeln(len);
 
    foreach (immutable r; 1 .. n + 1)
    {
        foreach (immutable c; 1 .. n + 1)
        {
            auto a = (n * ((r + c - 1 + (n / 2)) % n)) + ((r + (2 * c) - 2) % n) + 1;
            // n(( I + J - 1 + ( n / 2 ) ) mod n ) + (( I + 2J - 2 ) mod n ) + 1
//        writeln("n = ",n, " r = ",r," c = ",c, " a = ",a );
          writef("%" ~ len ~ "d%s",a, " ");
        }
        writeln("");
    }
    ;
 
    writeln("\nMagic constant: ", ((n * n + 1) * n) / 2);
}}