FOR FREE CONTENT

Write a program to find whether a given matrix is magic or not.

Back to Programming

Description

Overview

A Magic matrix has the following properties :

a. n x n matrix of distinct element from 1 to n2 .

b. Sum of any row, column, prime diagonal and secondary diagonal is always equal.


Example : 


The following matrix is a magic matrix:

4 9 2

3 5 7

8 1 6 


This matrix has all the properties of a magic matrix :

·     All the elements in the matrix are unique

·     Sum of any row = 15

·     Sum of any column = 15

·     Sum of any prime diagonal =15

·     Sum of any secondary diagonal = 15


Algorithm

Algorithm:


Input: 

 A matrix


Output:

 Displays if the given matrix is a magic matrix or not

 

Algo:


Step 1: Start

 

Step 2:Defining magicMatrix function

int magicMatrix(int n, int matrix[][n])

Set primeDiagonalSum <=  0

for i = 0 to i < n repeat

Set primeDiagonalSum <=  primeDiagonalSum + matrix[i][i]

Set I <= i + 1

Set secondaryDiagonalSum <= 0

for i = 0 to i < n repeat

Set secondaryDiagonalSum <= secondaryDiagonalSum + matrix[i][n-1-i]

Set i <= i + 1

Check if(primeDiagonalSum ≠ secondaryDiagonalSum)

Return 0

End if

for i = 0 to i < n repeat

Set rowSum <= 0

for j = 0 to j < n repeat

Set rowSum <= rowSum + matrix[i][j]

Set j <= j + 1

Check if(rowSum ≠ primeDiagonalSum)

Return 0

End if

Set i <= i + 1

for i = 0 to i < n repeat

Set columnSum <= 0

for j = 0 to j < n repeat

Set columnSum <= columnSum + matrix[i][j]

Set j <= j + 1

Check if(columnSum ≠ primeDiagonalSum)

Return 0

End if

Set i <= i + 1

Return 1

 

 

Step 3: Defining main function

Set int matrix[100][100] <= null

Set int i <= null

Set int j <= null

Set int n <= null

Display “Enter the Size of the Matrix”

Read n

Display “Enter the matrix”

for i = 0 to i < n repeat

for j = 0 to j < n repeat

Read matrix[i][j]

Set j <=  j + 1

Set i <= i + 1

Display “The matrix is” 

for i = 0 to i < n repeat

Display “\n”

for j = 0 to j < n repeat

Display matrix[i][j]

Set j <=  j + 1

Set i <= i + 1

Check if(Call magicMatrix(n, matrix))

Display “The given matrix is a magic matrix”

Else

Display “The given matrix is not a magic matrix”

End if

Return 0

 

Step 13: Stop

Code

Applications:

a. It is used in cryptography and the creation of ciphers.

b. Also it is played as a game.


 Advantage:

1. No extra space is required for this program as dynamic memory allocation is used here.


 Disadvantage:

2. Time complexity is quite high, O(n*n).


 Time complexity:

If the size of the matrix is n x n . Then the time complexity will be O(n*n) as we need to iterate over the row and columns of the matrix.


 Space Complexity:

No extra space is required in this code, so space complexity O(1) .