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
prime = [ ] NEW_LINE def buildSieve ( sum ) : NEW_LINE INDENT global prime NEW_LINE prime = [ True for i in range ( sum + 1 ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p < ( sum + 1 ) ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , sum + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def getSum ( a ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT for j in range ( 5 ) : NEW_LINE INDENT s += a [ i ] [ j ] NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT def checkIndex ( n , m , a ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( prime [ i + j ] and not prime [ a [ i ] [ j ] ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE m = 5 NEW_LINE a = [ [ 1 , 2 , 3 , 2 , 2 ] , [ 2 , 2 , 7 , 7 , 7 ] , [ 7 , 7 , 21 , 7 , 10 ] , [ 2 , 2 , 3 , 6 , 7 ] ] NEW_LINE sum = getSum ( a ) NEW_LINE buildSieve ( sum ) NEW_LINE if ( prime [ sum ] and checkIndex ( n , m , a ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT