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)


_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