In: Computer Science
PYTHON: Implement the following algorithm to construct magic n × n squares; it works only if n is odd.
row ← n - 1
column ← n/2
for k = 1 . . . n2 do
Place k at [row][column]
Increment row and column
if the row or column is n then
replace it with 0
end if
if the element at [row][column] has already been filled then
Set row and column to their previous values
Decrement row end if end for
Here is the 5 × 5 square that you get if you follow this algorithm:
11 18 25 2 9
10 12 19 21 3
4 6 13 20 22
23 5 7 14 16
17 24 1 8 15
Write a program whose input is the number n and whose output is the magic square of order n if n is odd.
Please solve in Python
PYTHON Program:
n= int(input("Enter the value of n: "))
if n%2==0:
print("Even value entered. Expecting an odd number.")
else:
arr= [[0 for i in range(n)] for j in range(n)]
row = n-1
column = n//2
for k in range(1,n*n+1):
arr[row][column] = k
newrow = row + 1
newcolumn = column + 1
if newrow == n:
newrow = 0
if newcolumn == n:
newcolumn = 0
if arr[newrow][newcolumn] != 0:
row = row-1
else:
row = newrow
column = newcolumn
print("Magic Square of order",n,"x",n,":")
for i in range(0,n):
for j in range(0,n):
print(arr[i][j],end=" ")
print(" ")
Output: