-
Notifications
You must be signed in to change notification settings - Fork 0
/
Magic Square.py
60 lines (47 loc) · 1.1 KB
/
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 23:01:36 2019
@author: Satvik Chachra
"""
def magic_square(n):
ms = []
for i in range(n):
l=[]
for j in range(n):
l.append(0)
ms.append(l)
#position of 1
i = n//2
j = n-1
mat = n*n
count = 1
while(count<=mat):
#stay in boundary of matrix
if(j==n and i == -1):
i=0
j=n-2
elif(j==n):
j=0
elif(i<0):
i=n-1
#if already placed
if(ms[i][j]!=0):
i = i+1
j = j-2
continue
else:
ms[i][j] = count
count = count+1
i = i-1
j = j+1
pr(n,ms)
def pr(n,ms):
for i in range(n):
for j in range(n):
print(ms[i][j],end=" ")
print()
n = int(input("Enter the order of square matrix: "))
#matrix constant
m = int((n*((n*n)+1))/2)
print("matrix constant = ",m)
magic_square(n)