Skip to content

Commit fb3f3ff

Browse files
authored
Add MagicSquare (TheAlgorithms#2411)
1 parent db85993 commit fb3f3ff

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Maths/MagicSquare.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.*;
2+
/*A magic square of order n is an arrangement of distinct n^2 integers,in a square, such that the n numbers in all
3+
rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to n^2.*/
4+
public class MagicSquare {
5+
6+
public static void main(String[] args) {
7+
8+
Scanner sc = new Scanner(System.in);
9+
System.out.print("Input a number: ");
10+
int num = sc.nextInt();
11+
if ((num % 2 == 0) || (num <=0 ))
12+
{
13+
System.out.print("Input number must be odd and >0");
14+
System.exit(0);
15+
}
16+
17+
int[][] magic_square = new int[num][num];
18+
19+
int row_num = num/2;
20+
int col_num = num-1;
21+
magic_square[row_num][col_num] = 1;
22+
23+
for (int i = 2; i <= num*num; i++) {
24+
if (magic_square[(row_num - 1+num) % num][(col_num + 1) % num] == 0) {
25+
row_num = (row_num - 1+num) % num;
26+
col_num = (col_num + 1) % num;
27+
}
28+
else {
29+
col_num = (col_num - 1 +num) % num;
30+
}
31+
magic_square[row_num][col_num] = i;
32+
}
33+
34+
// print the square
35+
for (int i = 0; i < num; i++) {
36+
for (int j = 0; j < num; j++) {
37+
if (magic_square[i][j] < 10) System.out.print(" ");
38+
if (magic_square[i][j] < 100) System.out.print(" ");
39+
System.out.print(magic_square[i][j] + " ");
40+
}
41+
System.out.println();
42+
}
43+
44+
}
45+
}

0 commit comments

Comments
 (0)