1.
Introduction
2.
Magic Square
3.
The Magic Square's Filling Rules
4.
Program in Java
4.1.
Output
5.
Program in C++
5.1.
Output
6.
Program in Python
7.
Output
8.
8.1.
How many different kinds of magic squares are there?
8.2.
What makes magic squares unique?
8.3.
Can you make a magic square repeat number?
8.4.
Is it possible to have an unlimited number of magic squares?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

# Magic Square (Odd Order)

Ayush Mishra
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

## Introduction

In this article, we will discuss the odd-order magic square and its implementation in different languages. Magic squares are one of the most basic types of logic puzzles, and they're a terrific way to get started with problem-solving approaches that aren't limited to typical arithmetic procedures. Each square is divided into cells, and the rules state that every row, column, or diagonal in the square must add up to the same number.

Recommended Topic, Array Implementation of Queue and Rabin Karp Algorithm

## Magic Square

A magic square is a square array of numbers made up of separate positive integers 1, 2,..., k^2 that is organized so that the total of the n numbers on any horizontal, vertical, or major diagonal line is always the same number.

This formula will find the sum of each row, column, or diagonal.

M = k(k^2+ 1)/2

This square only works with odd n values and does not operate with even integers.

Let's consider the below given an example:

``````Size of the Magic Square 3
-----------------------
8   3   4
1   5   9
6   7   2

Each row and column have a total = 3*(3^2+1)/2 = 15

Size of the Magic Square 5
----------------------
19  8  22  11  5
12  1  20  9   23
10  24 13  2   16
3   17 6   25  14
21  15 4   18  7

Each row and column have a total = 5*(5^2+1)/2 = 65``````
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

## The Magic Square's Filling Rules

Let's talk about some of the concepts that will help us write the rules for filling the magic square. One thing is certain: every number from 1 to k^2 may be found in the magic square. We will place the number 1 at the spot (k/ 2, k-1), and then each row and column will be considered circular and, therefore, will wrap around.

Rule 1: The location of the next number is determined by reducing the row number of the previously filled number by one and raising the column number of the previously filled number by one at any point. If the computed location of the row reaches -1 at any point in time, we shall wrap it around to k - 1. Similarly, if the column's computed position reaches k, we'll wrap it to 0.

Rule 2: If a number is already present in the magic square at the estimated location, the computed position of the column is reduced by two, and the computed position of the row is increased by one.

Rule 3:If the computed row position is -1, and the computed column position is k, the new position will be: (0,k - 2).

For a better understanding, consider the following example:-

2 7 6

9 5 1

4 3 8

The square matrix above is of order 3 and has 9 elements.

Steps:-

1. Position of digit 1 is (3 / 2, 3 - 1) = (1, 2)
2. Position of digit 2 is (1 - 1, 2 + 1) = (0, 3) = (0, 0)
3. Position of digit 3 is (0 - 1, 0 + 1) = (-1, 1) = (3 - 1, 1) = (2, 1)
4. Position of digit 4 is (2 - 1, 1 + 1) = (1, 2)
5. Position of digit 5 is (2 - 1, 0 + 1) = (1, 1)
6. Position of digit 6 is (1 - 1, 1 + 1) = (0, 2)
7. Position of digit 7 is  ( 0 - 1, 2 + 1) = (-1, 3) = (0, 3 - 2) = (0, 1)
8. Position of digit 8 is ( 0 - 1, 1 + 1) = (-1, 2) = (3 - 1, 2) = (2, 2)
9. Position of digit 9 is  ( 2 - 1, 2 + 1) = (1, 3) = (1, 0)

## Program in Java

``````import java.util.*;
class Magic_Square
{
//  Create the odd-sized magic squares with this method.

public static void creatingSquare(int n)
{
int mgsqr[][] = new int[n][n];
int r = n / 2;
int c = n - 1;
int i =1;
while(i<=n*n)
{
if (r == -1 && c == n) // 3rd rule
{
c = n - 2;
r = 0;
}
else
{
// If the following number is out of the range, use the first rule as a guide.
if (c == n)
{
c = 0;
}
if (r < 0)
{
r = n - 1;
}
}
if (mgsqr[r][c] != 0)   // second rule
{
c = c - 2;
r = r + 1;
continue;
}
else
{
mgsqr[r][c] = i;
i =i+1;
}
c = c + 1;
r = r - 1;
}
System.out.println("The Magic Square for " + n);
System.out.println();
System.out.println("Sum of each column or row " + n* (n*n + 1) / 2);
System.out.println();
for (r = 0; r < n; r++)
{
for (c = 0; c < n; c++)
{
System.out.print(mgsqr[r][c] + " ");
}
System.out.println();
}
}
public static void main(String args[])
{
int n =7;
Magic_Square object = new Magic_Square();
object.creatingSquare(n);
}
}``````

### Output

``````The Magic Square for 7

Sum of each column or row 175

20 12 4 45 37 29 28
11 3 44 36 35 27 19
2 43 42 34 26 18 10
49 41 33 25 17 9 1
40 32 24 16 8 7 48
31 23 15 14 6 47 39
22 21 13 5 46 38 30``````

## Program in C++

``````#include <bits/stdc++.h>
using namespace std;

//  Create the odd-sized magic squares with this method.
void creatingSquare(int n)
{
int mgsqr[n][n];
memset(mgsqr, 0, sizeof(mgsqr));
int r = n / 2;
int c = n - 1;
int num =1;
while(num <= n * n)
{
if (r == -1 && c == n) // 3rd rule
{
c = n - 2;
r = 0;
}
else
{
// If the following number is out of the range, use the first rule as a guide.

if (c == n)
{
c= 0;
}
if (r < 0)
{
r = n - 1;
}
}
if(mgsqr[r][c]) // 2nd rule
{
c -= 2;
r++;
continue;
}
else
{
mgsqr[r][c] = num++;
}
c++;
r--; // 1st rule
}

cout << "The Magic Square for n=" << n<< ":\nSum of ""each row or column "<< n * (n * n + 1) / 2 << ":\n";

for (r = 0; r < n; r++)
{
for (c = 0; c < n; c++)
{
// setw(4) is used to ensure that the matrix is printed in a square format.
cout << setw(4) << mgsqr[r][c] << " ";
}
cout << endl;
}
}
int main()
{
int n = 7;
creatingSquare(n);
return 0;
}``````

### Output

``````The Magic Square for n=7:
Sum of each row or column 175:
20   12    4   45   37   29   28
11    3   44   36   35   27   19
2   43   42   34   26   18   10
49   41   33   25   17    9    1
40   32   24   16    8    7   48
31   23   15   14    6   47   39
22   21   13    5   46   38   30 ``````

## Program in Python

``````def creatingSquare(n):

# 2-D array with all slots set to 0
mgsqr = [[0 for x in range(n)]
for y in range(n)]

# initialize position of 1
r = n // 2
c = n - 1
# Fill the magic square by placing values
num = 1
while num <= (n * n):
if r == -1 and c == n:  # 3rd condition
c = n - 2
r = 0
else:
# next number goes out of right side of square
if c == n:
c = 0
# next number goes out of upper side
if r < 0:
r = n - 1

if mgsqr[int(r)][int(c)]:  # 2nd condition
c= c - 2
r= r+ 1
continue
else:
mgsqr[int(r)][int(c)] = num
num = num + 1

c = c + 1
r = r - 1  # 1st condition

# Printing magic square
print("Magic Square for n =", n)
print("Sum of each row or column",
n * (n * n + 1) // 2, "\n")

for i in range(0, n):
for j in range(0, n):
print('%2d ' % (mgsqr[i][j]),
end='')

if j == n - 1:
print()

n = 7
creatingSquare(n)``````

## Output

``````Magic Square for n = 7
Sum of each row or column 175

20 12  4 45 37 29 28
11  3 44 36 35 27 19
2 43 42 34 26 18 10
49 41 33 25 17  9  1
40 32 24 16  8  7 48
31 23 15 14  6 47 39
22 21 13  5 46 38 30 ``````

Check out this problem - Subarray Sum Divisible By K

### How many different kinds of magic squares are there?

As a result, there is just one magic square. The eight patterns are rotations and reflections that match the square's symmetries.

### What makes magic squares unique?

Magic Squares are square grids that have a unique numerical layout. These numbers are unique in that they add up to the same number in every row, column, and diagonal.

### Can you make a magic square repeat number?

Many magic squares would become trivially easy if you could repeat integers, such as a grid comprised entirely of 1s that tallied up to 3! That isn't really remarkable.

### Is it possible to have an unlimited number of magic squares?

A magic square is an nĂ—n grid of integers in which the sum of the number in each row, column, and diagonal equals a magic constant M. This process produces an endless magic square with zero sums in each row, column, and diagonal.

## Conclusion

In this blog, we have discussed the odd-order magic square. We introduced the magic square, its formula, and algorithm and implemented it in different languages.

We hope this blog has improved your understanding of the odd-order magic square.

To learn more and become more adept read our blogs on Operations on MatricesConstruct a Linked List from a 2D Matrix, Matrix Chain Multiplication, and Types of Matrix for additional information and must-visit our practice site  Coding Ninjas Studio and practice top problems, take Mock Tests, practice extra SQL questions here, and read educational articles and interview experiences. Please vote for our blog so that other ninjas can benefit from it.

Happy Learning!

Live masterclass