Check if the Matrix follows the given constraints or not | Stores true at prime indices ; Function to generate the prime numbers using Sieve of Eratosthenes ; If p is still true ; Mark all multiples of p ; Function returns sum of all elements of matrix ; Function to check if for all prime ( i + j ) , a [ i ] [ j ] is prime ; If index is prime ; Driver Code ; Check for both conditions
var prime = [ ] ; function buildSieve ( sum ) { prime = Array ( sum + 1 ) . fill ( true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( var p = 2 ; p * p < ( sum + 1 ) ; p ++ ) { if ( prime [ p ] == true ) { for ( var i = p * 2 ; i < ( sum + 1 ) ; i += p ) prime [ i ] = false ; } } } function getSum ( a ) { var s = 0 ; for ( var i = 0 ; i < 4 ; i ++ ) for ( var j = 0 ; j < 5 ; j ++ ) s += a [ i ] [ j ] ; return s ; } function checkIndex ( n , m , a ) { for ( var i = 0 ; i < n ; i ++ ) for ( var j = 0 ; j < m ; j ++ ) { if ( prime [ i + j ] && ! prime [ a [ i ] [ j ] ] ) { return false ; } } return true ; } var n = 4 , m = 5 ; var a = [ [ 1 , 2 , 3 , 2 , 2 ] , [ 2 , 2 , 7 , 7 , 7 ] , [ 7 , 7 , 21 , 7 , 10 ] , [ 2 , 2 , 3 , 6 , 7 ] ] ; var sum = getSum ( a ) ; buildSieve ( sum ) ; if ( prime [ sum ] && checkIndex ( n , m , a ) ) { document . write ( " " ) ; } else document . write ( " " ) ;