A program to demonstrate MagicSquare in Python
In this article, we are going to study Magic Square in Python. We will learn about Magic Square, its steps and algorithm, and its code implementation through Python programming language.
To begin with, What is a Magic Square? A Magic Square of any order say, ‘n’, is the arrangement of distinct numbers(positive integers) from 1 to n^2 in an n*n matrix or grid where the sum of each row/column/diagonal is equal. This sum is known as the magic sum or the magic constant of the magic square. The formula to calculate this magic sum(M) is:
M = n(n^2+1)/2, where’ n’ is the order of Magic Square to be calculated.
- M = 3* [(3^2 + 1) / 2]
- M = 3*[(9+1) / 2 ]
- M = 3 * (10 / 2)
- M = 3 * (5)
- M = 15
Hence, The magic sum for a 3×3 square is 15 and the Magic Square is:
2 7 6
9 5 1
4 3 8
Here, 2+7+6 = 9+5+1 = 4+3+8 = 2+9+4 = 7+5+3 = 6+1+8 = 2+5+8 = 6+5+4 = 15
Steps and Algorithms to Implement Magic Square
- Step 1: Start filling the matrix with integer 1. Locate 1 at position (n/2, n-1).
- Step 2: Now proceed with the next integer number 2. Let’s say the position of 1 i.e, (n/2, n-1) is (m, n), then the position of the next item to be inserted i.e, 2 will be located at (m-1, n+1) position. If anytime the calculated row position comes at -1 then locate it at n-1 and if the column position comes at n, then locate it at 0.
- Step 3: If the calculated location/position has already been filled, then decrement the column position by 2 and increment the row position by 1.
- Step 4: Anytime if the row position comes -1 and column comes at n, switch the location to (0, n-2).
Function Code for Magic Square in Python
def magic_square(n): #creating the n*n matrix named magicSq magicSq=[] for i in range(n): k=[] for j in range(n): k.append(0) magicSq.append(k) #calculating the first position row=n//2 col=n-1 num=n*n count=1 while(count<=num): if(row==-1 and col==n): #condition/step 4 col=n-2 row=0 else: if(col==n): #if column comes at n, replace it with 0 col=0 if(row<0): # if row comes at 0, replace it with n-1 row=n-1 if(magicSq[row][col]!=0): #step 3 col=col-2 row=row+1 continue else: magicSq[row][col]=count #insering the values count+=1 row=row-1 #step 2( normal case) col=col+1 #printing the Magic Square for i in range(n): for j in range(n): print(magicSq[i][j],end=" ") print()
It is amazing to know that a normal desktop or computer is not sufficient to take calculate the Magic Square of any even integer.
So here, let’s take examples of odd numbers like 3 and 5.
magic_square(3) #This line will execute the above function and print the magic Square for integer 3.
Output:
2 7 6 9 5 1 4 3 8
for 5,
magic_square(5)
Output:
9 3 22 16 15 2 21 20 14 8 25 19 13 7 1 18 12 6 5 24 11 10 4 23 17
for 7,
magic_square(7)
Output:
20 12 4 45 37 29 28 11 3 44 36 35 27 19 2 43 42 34 26 18 10 49 41 33 25 17 9 1 40 32 24 16 8 7 48 31 23 15 14 6 47 39 22 21 13 5 46 38 30
and so on.
Leave a Reply