-
Notifications
You must be signed in to change notification settings - Fork 0
/
Magic Square.py
43 lines (38 loc) · 922 Bytes
/
Magic Square.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def magic_square(n):
magicSquare = [[0 for i in range(n)] for j in range(n)]
MagicNum = n*(n**2 + 1)/2
print("Magic Number:",MagicNum)
i = n//2
j = n-1
num = n*n
count = 1
while(count<=num):
if(i == -1 and j == n):
j = n-2
i = 0
else:
if(j == n):
j = 0
if(i<0):
i = n-1
if(magicSquare[i][j] != 0):
j = j-2
i = i+1
continue
else:
magicSquare[i][j] = count
count += 1
i = i-1
j = j+1
return magicSquare
if __name__ == "__main__":
while True:
n = int(input("Enter a num: "))
if n%2 == 0:
print("Enter an odd number")
else:
break
ans = magic_square(n)
print("Magic Square of order",n,":")
for i in ans:
print(i)