Question
A Magic Square is a square matrix of consecutive integers, such that the integers in each row, each column and each diagonal add up to
A Magic Square is a square matrix of consecutive integers, such that the integers in each row, each column and each diagonal add up to the same sum. For instance, the first 3 x 3 matrix below is a magic square and the rows, columns and diagonal add up to 15. The second 5 x 5 matrix has 25 consecutive integers - starting at 1 - where each row, column and diagonal has the sum of 65.
8 | 1 | 6 |
3 | 5 | 7 |
5 | 9 | 2 |
17 | 24 | 1 | 8 | 15 |
23 | 5 | 7 | 14 | 16 |
4 | 6 | 13 | 20 | 22 |
10 | 12 | 19 | 21 | 3 |
11 | 18 | 25 | 2 | 9 |
Magic squares have special algorithms that will create a magic square for any size. For the purpose of this question you are only concerned with odd-sized magic squares, like the two above. There are different algorithms for even-sided magic squares. The steps below describe the algorithm for any odd-sized magic square size 3 or larger.
- Start number 1 in the top row, middle column.
- Place the next number one row higher and one column to the right.
- If (the number mod size) = 1, place the next number one row lower. In the5 x 5 square above, size = 5. So, 6 is below 5, 11 is below 10, 16 is below 15,
Wrap around: If the above instructions ask you to place a number:
- above the first row, place it in the last row.
- below the last row, place it in the first row.
- to the right of the last column, place it in the first column.
Write a program to prompt for an odd number n less than 20, and solve that n-sized magic square.
Name the class and file name Magic.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started