patternMinor
Magic Square Check for NxN Matrix - with Minimum Complexity?
Viewed 0 times
withmagicminimumforsquarecheckmatrixcomplexitynxn
Problem
Is there any algorithm that works better than $\Theta(n^2)$ to verify whether a square matrix is a magic one? (E.g. such as sum of all the rows, cols and diagonally are equal to each other).
I did see someone mention a $O(n)$ time on a website a few days ago but could not figure out how.
I did see someone mention a $O(n)$ time on a website a few days ago but could not figure out how.
Solution
If you have an $N \times N$ matrix, then it has $N^2$ entries, and as you need to check all entries at least once to see if the square is a magic square, any algorithm must have a running time of $\Omega(N^2)$.
For a square to be a magic square, all rows, columns and both diagonals must sum to the same number. There are $N$ rows, $N$ columns and 2 diagonals, each of which have $N$ entries, so you can check this property in $O((2N+2)N) = O(N^2)$ time.
Combining the above: verifying the magicness of a square is in $\Theta(N^2)$.
For a square to be a magic square, all rows, columns and both diagonals must sum to the same number. There are $N$ rows, $N$ columns and 2 diagonals, each of which have $N$ entries, so you can check this property in $O((2N+2)N) = O(N^2)$ time.
Combining the above: verifying the magicness of a square is in $\Theta(N^2)$.
Context
StackExchange Computer Science Q#1460, answer score: 4
Revisions (0)
No revisions yet.