10000 Added the magic square algorithm · CO18326/python@8c57789 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8c57789

Browse files
Added the magic square algorithm
1 parent adb00e9 commit 8c57789

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

math/magic_square.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
3+
4+
"""A magic square is an N×N grid of numbers in which the entries in each row, column and main diagonal sum to the same number (equal to N(N2+1)/2)"""
5+
6+
7+
import numpy as np
8+
9+
10+
print("Hi! Welcome to the magic square algorithm")
11+
print("Please enter the number for which you would want a magic sqaure to be printed. Please enter an odd number")
12+
13+
# The odd number for which the magic square is created is stored in the variable N
14+
15+
N = int(input())
16+
17+
# create a matrix with values 0 using numpy. The datatype is int for the elements in the matrix
18+
magic_square = np.zeros((N,N), dtype=int)
19+
20+
n = 1
21+
i, j = 0, N//2
22+
23+
# n iterates from 1 to N**2. The loop exits when n is equal to N**2
24+
25+
while n <= N**2:
26+
# Start in the middle of the first row.
< 8EB1 /code>
27+
# (i = 0 and j = N//2 ) and the element at magic_square[i,j] is the middle in the first row.
28+
# insert n = 1 to begin with at magic_square[i,j]
29+
magic_square[i, j] = n
30+
# increment n by 1
31+
n += 1
32+
# Move diagonally up and right, wrapping to the first column or last row if the move leads outside the grid
33+
34+
new_i, new_j = (i-1) % N, (j+1)% N
35+
36+
# if the cell is already filled with a number, move vertically down one space.
37+
if magic_square[new_i, new_j]:
38+
i += 1
39+
else:
40+
i, j = new_i, new_j
41+
42+
print(magic_square)

0 commit comments

Comments
 (0)
0