Check given matrix is magic square or not | Javascript program to check whether a given matrix is magic matrix or not ; Returns true if mat [ ] [ ] is magic square , else returns false . ; calculate the sum of the prime diagonal ; the secondary diagonal ; For sums of Rows ; check if every row sum is equal to prime diagonal sum ; For sums of Columns ; check if every column sum is equal to prime diagonal sum ; driver program to test above function
var N = 3 function isMagicSquare ( mat ) { var sum = 0 , sum2 = 0 ; for ( var i = 0 ; i < N ; i ++ ) sum = sum + mat [ i ] [ i ] ; for ( var i = 0 ; i < N ; i ++ ) sum2 = sum2 + mat [ i ] [ N - 1 - i ] ; if ( sum != sum2 ) return false ; for ( var i = 0 ; i < N ; i ++ ) { var rowSum = 0 ; for ( var j = 0 ; j < N ; j ++ ) rowSum += mat [ i ] [ j ] ; if ( rowSum != sum ) return false ; } for ( var i = 0 ; i < N ; i ++ ) { var colSum = 0 ; for ( var j = 0 ; j < N ; j ++ ) colSum += mat [ j ] [ i ] ; if ( sum != colSum ) return false ; } return true ; } var mat = [ [ 2 , 7 , 6 ] , [ 9 , 5 , 1 ] , [ 4 , 3 , 8 ] ] ; if ( isMagicSquare ( mat ) ) document . write ( " " ) ; else document . write ( " " ) ;