Radeen10-_

Magic Square

Feb 5th, 2021 (edited)
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. # Python program to generate
  2. # odd sized magic squares
  3. # A function to generate odd
  4. # sized magic squares
  5.  
  6.  
  7. def generateSquare(n):
  8.  
  9.     # 2-D array with all
  10.     # slots set to 0
  11.     magicSquare = [[0 for x in range(n)]
  12.                 for y in range(n)]
  13.  
  14.     # initialize position of 1
  15.     i = n / 2
  16.     j = n - 1
  17.  
  18.     # Fill the magic square
  19.     # by placing values
  20.     num = 1
  21.     while num <= (n * n):
  22.         if i == -1 and j == n: # 3rd condition
  23.             j = n - 2
  24.             i = 0
  25.         else:
  26.  
  27.             # next number goes out of
  28.             # right side of square
  29.             if j == n:
  30.                 j = 0
  31.  
  32.             # next number goes
  33.             # out of upper side
  34.             if i < 0:
  35.                 i = n - 1
  36.  
  37.         if magicSquare[int(i)][int(j)]: # 2nd condition
  38.             j = j - 2
  39.             i = i + 1
  40.             continue
  41.         else:
  42.             magicSquare[int(i)][int(j)] = num
  43.             num = num + 1
  44.  
  45.         j = j + 1
  46.         i = i - 1 # 1st condition
  47.  
  48.     # Printing magic square
  49.     print("Magic Squre for n =", n)
  50.     print("Sum of each row or column",
  51.         n * (n * n + 1) / 2, "\n")
  52.  
  53.     for i in range(0, n):
  54.         for j in range(0, n):
  55.             print('%2d ' % (magicSquare[i][j]),
  56.                 end='')
  57.  
  58.             # To display output
  59.             # in matrix form
  60.             if j == n - 1:
  61.                 print()
  62.  
  63. # Driver Code
  64.  
  65.  
  66. # Works only when n is odd
  67. n = 7
  68. generateSquare(n)
  69.  
  70.  
  71.  
Add Comment
Please, Sign In to add comment