Java Program to Check Given Matrix is Magic Square or Not2 May 2025 | 5 min read A magic square is a square matrix (an (n times n) grid) of unique positive integers organized in such a way that the total of the numbers in each row, column, and both main diagonals is equal. This constant sum is known as the magical constant. Magic squares have captivated mathematicians and enthusiasts for generations, combining parts of number theory and symmetry in novel ways. Magic SquareA standard magic square of order (n) employs numbers between (1) and (n^2).
The magic constant (or magic sum) for an (n times n) magic square can be calculated using the formula: Magic Constant = n(n^2 + 1)/2 For example, in a (3 times 3) magic square, the magic constant is: Magic Constant = 3(3^2 + 1)/2 = 3 * 10/2 = 15 Properties of a Magic SquareMagic squares exhibit various interesting properties:
Types of Magic SquaresThere are several types of magic squares based on properties and configurations:
Method for Determining Whether a Matrix is a Magic SquareIn order to identify if a given (n x n) matrix is a magic square, we must:
Matrix Square Java ProgramLet's implement the above steps in a Java program. File Name: MagicSquareChecker.java Output: The given matrix is a magic square. ExplanationThe Java code above defines a colass, 'MagicSquareChecker', which has a method isMagicSquare() that receives a matrix (2D array) as input and assesses if it meets the criteria for a magic square. The algorithm first determines if the matrix is square, and then calculates the magic constant based on its size. It then iterates through each row and column to see if their sums equal the magic constant. It also checks the sums of both main diagonals. Finally, the function ensures that all numbers in the matrix are distinct and range from (1) to ( n^2 ). If all these checks pass, the matrix is identified as a magic square. In the main() method, a sample ( 3 times 3 ) matrix is tested, and a message is displayed indicating whether it is a magic square. This approach effectively identifies magic squares by verifying both structural properties and numerical conditions, ensuring the output is accurate and efficient. Complexity AnalysisThe time complexity of this algorithm is (O(n^2)), where (n) is the dimension of the matrix. This is because we must iterate through all elements to check row sums, column sums, and both diagonals, as well as to confirm the presence of distinct values. Each check requires scanning all elements, resulting in a combined complexity of (O(n^2) ). The space complexity is (O(n^2)) due to the input matrix itself and an additional (O(n^2) ) for the boolean array used to track uniqueness, making the overall space complexity (O(n^2)) as well. This is efficient for small to medium-sized matrices, making the algorithm suitable for general-purpose magic square validation. ConclusionMagic squares are fascinating mathematical constructs characterized by unique properties of symmetry and numerical patterns. The Java code provided efficiently checks if a given matrix qualifies as a magic square by verifying the sum consistency of rows, columns, and diagonals, and ensuring the matrix contains unique elements within a specified range. This approach ensures the matrix is validated against the strict requirements for magic squares, providing a robust solution suitable for square matrices of any size. By implementing this algorithm, we gain deeper insight into the computational requirements and structure of magic squares, further appreciating their complexity and elegance. Next TopicJava 32-Bit Download For Windows 10 |
The goal is to get the outcome of the items in the Vertical Zig-Zag traversal order given a Binary Tree. A tree's vertical zigzag traversal is described as follows: List the first level's elements in the correct order from right to left; if no parts remain, move...
6 min read
Functions are used to break and divide a huge code into small chunks so that the code becomes more understandable and thus reduces the complexity of the code. Arrays are the homogenous data structures for reducing the code complexity, increasing efficiency, and reducing the execution time...
6 min read
Big Data is a huge volume of data collection, which is growing exponentially with time. Traditional database management tools can not handle big data. So, a large size of data is managed and processed using big data tools. There are several Big Data tools available to...
8 min read
? We can check whether an integer exists in a range in Java using conditional statements with the lower and upper bounds of the range. To check whether an integer exists in a range, we can use the following steps: Define the range (start and end) values. Compare the integer...
6 min read
In programming, sorting is important because it puts elements of an array in a certain order. The widely used order is alphabetical order or natural order. The sorting is used for canonicalizing (the process of converting data in the standard form) data and for producing a...
3 min read
Checked exceptions are the exceptions that are checked at compile-time. It is also known as compile-time exceptions. The Java compiler forces developers to handle it. If any method that can throw a check exception does not handle it using a try-catch block or declare it using...
7 min read
In today's fast-paced world, staying organized and keeping track of important tasks and events is crucial. A reminder program can be a handy tool to help manage our busy schedules effectively. In this section, we will explore how to develop a reminder program in Java. We'll...
6 min read
In this section, we are going to learn how one can use minimum coins for making a given value. The problem of making a given value using minimum coins is a variation of coin change problem. In this problem, a value Y is given. The task is...
6 min read
In this section, we will create Java programs to find the sum of digits of a number in Java. In order to find the sum of digits of a number, we must familiar with the Java loops and operators. Steps to Find the Enter any integer...
6 min read
Among other optimisations in Java development programming the object pooling pattern serves to handle efficient object reuse management, especially in costly object life cycle events. The following article explains Java object creation techniques for establishing multiple pools of objects with variable sizes while discussing system...
5 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India