Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Magic Square
3.
Algorithm
4.
Program
4.1.
C++ Code
4.1.1.
Output:
4.2.
Java Code
4.2.1.
Output :
4.3.
Python Code
4.3.1.
Output
5.
Frequently Asked Questions
5.1.
How many different kinds of magic squares are there?
5.2.
What makes magic squares unique?
5.3.
Can you make a magic square repeat number?
5.4.
Is it possible to have an unlimited number of magic squares?
6.
Conclusion
Last Updated: Mar 27, 2024

Magic Square Matrix

Author Neha kumari
0 upvote

Introduction

In this article, we will discuss whether the given matrix is a magic square or not and its implementation in different languages. Magic squares are one of the most basic types of logic puzzles. They're a terrific way to start 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. If you are not familiar with the concept of Magic Squares be sure to check out our articles, Magic Squares (Even Order) and Magic Squares (Odd Order).

Magic Square

A magic square of sequence n is the positioning of n2 numbers, generally actual numbers, in a square, with the end goal that the n numbers in all rows, all columns, and the two diagonals total to a similar value. A magic square contains the integers from 1 to n2.

In the magic square, the constant value is equal to the sum of each row, column, and matrix diagonals.This constant value is calculated with: n(n2+1)/2.Where n is the constant value here. 

This magic constant of any square relies on the value of n.

For example, to understand the magic square of a given matrix.

Output: Magic Square

In the above example, the sum of each row, each column, and the two diagonals are all equal to one constant value, which is 18. Thus it is a magic square of order 3. Similarly, there can be a magic square with an order 4 matrix.

On the other hand, consider the example below:

Output: Not a magic square.

Here, the sum of each row, column and diagonal is not equal.Thus it’s not a magic square.

Steps to check for a magic square

  1. Calculate the sum of the prime diagonal
  2. Then find the sum of each row and column.
  3. Check whether the sum of prime diagonals is the same as the sum of rows and columns.If yes, then it’s a magic square.

Diagramatic representation of magic square:

  1. Calculate the sum of each row. Here the sum of each row is 18.
     


 

2. Calculate the sum of each column. Here the sum of each column is 18.

3. Calculate the sum of both diagonals. Here the sum of both diagonals is 18.

Thus we can say that a given matrix of any order, maybe n =3 or n=4 will be a magic square if it fulfils the above three conditions.

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

Algorithm

  1.  Initialize a matrix as matr[][] along with declaring variables
  2.  a return type function to return the result at the end utilizing function calls 
  3.  Declare variable sum and calculate the sum of prime diagonal
  4.  use of for loop for finding some of the rows
  5.  use of for loop for finding some of the columns 
  6.  if-else statement for checking the sum of both rows and columns is the same as that of diagonals
  7.  primary function with input matrix values for checking whether it's a magic square or not

Program

Program codes for checking whether a matrix is a square matrix or not using the algorithm mentioned above.

C++ Code

//C++ code in order to check for magic square for a matrix
#include <bits/stdc++.h> 
using namespace std;   
// it will return true if the matr[][] is a magic
//square otherwise it will return false
bool isMagicSquare(int matr[][N]) 
{  
//find the prime diagonal sum of the matrix
    int sum = 0;  
    for (int i = 0; i < N; i++) 
        sum = sum + matr[i][i]; 
  
    // sums of the rows in the matrix
    for (int i = 0; i < N; i++) { 
          
        int rowSum = 0;      
        for (int j = 0; j < N; j++) 
            rowSum += matr[i][j]; 
          
        // condition for each row sum to be same as sum of prime diagonal
        if (rowSum != sum) 
            return false; 
    } 
  
    // For sums of Columns 
    for (int i = 0; i < N; i++) { 
          
        int colSum = 0;      
        for (int j = 0; j < N; j++) 
            colSum += matr[j][i]; 
  
        // condition for each row sum to be the same as the sum of prime diagonal


        if (sum != colSum)  
        return false; 
    } 
  
    return true; 
} 
  
// program to check above function


int main() 
{ 
    int mat[][N] = {{ 3, 8, 7 }, 
                              { 10, 6, 2 }, 
                              { 5, 4, 9 }}; 
      
    if (isMagicSquare(mat)) 
        cout << "It’s a Magic Square"; 
    else
        cout << "It’s not a Magic Square"; 
      
    return 0; 
}

Output:

Java Code


import java.io.*;

class CN {
	
	static int N = 3;
	
	
	static boolean isMagicSquare(int mat[][])
	{
		
		int sumd1 = 0,sumd2=0;
		for (int i = 0; i < N; i++)
		{

			sumd1 += mat[i][i];
			sumd2 += mat[i][N-1-i];
		}
        
        //if the two diagonal sums are not equal then it isn't a magic square
		if(sumd1!=sumd2)
			return false;


		for (int i = 0; i < N; i++) {

			int rowSum = 0, colSum = 0;
			for (int j = 0; j < N; j++)
			{
				rowSum += mat[i][j];
				colSum += mat[j][i];
			}
			if (rowSum != colSum || colSum != sumd1)
				return false;
		}


		return true;
	}

	// driver program 
	public static void main(String[] args)
	{
		int mat[][] = {{ 3, 8, 7 },
					{ 10, 6, 2 },
					{ 5, 4, 9 }};

		if (isMagicSquare(mat))
			System.out.println("Its aMagic Square");
		else
			System.out.println("Its not a Magic Square");
	}
}

Output :

Python Code

def isMagicSquare( mat) :
   
   n = len(mat)
   
   sumd1=0
   sumd2=0
   
   for i in range(n):
      sumd1+=mat[i][i]
      sumd2+=mat[i][n-i-1]
      # if the two diagonal sums are not equal then it isn't a magic square
   
   if not(sumd1==sumd2):
      return False
   
   for i in range(n):
      
      # rowsum and column sum
      sumr=0
      sumc=0
      
      for j in range(n):
         sumr+=mat[i][j]
         sumc+=mat[j][i]
      
      if not(sumr==sumc==sumd1):
         return False
   
   return True
	
	
# Driver Code
mat = [ [ 3, 8, 7 ],
		[ 10, 6, 2],
		[ 5, 4, 9 ] ]
	

if (isMagicSquare(mat)) :
	print( "Its a Magic Square")
else :
	print( "Its not a magic Square")
	

Output

Also see,  Rabin Karp Algorithm

Frequently Asked Questions

How many different kinds of magic squares are there?

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 because 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 whether the given matrix is a magic square or not. 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.

Click here to learn about Data Structure here.

To learn more and become more adept read our blogs on Operations on MatricesConstruct a Linked List from a 2D Matrix, Book Allocation ProblemMatrix 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!

Previous article
Magic Square (Even order)
Next article
Markov Matrix
Live masterclass