File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments