Check if the Matrix follows the given constraints or not | Python3 implementation of the above approach ; Function checks if n is prime or not ; Corner case ; Check from 2 to sqrt ( n ) ; Function returns sum of all elements of matrix ; Stores the sum of the matrix ; Function to check if all a [ i ] [ j ] with prime ( i + j ) are prime ; If index is prime ; If element not prime ; Driver code ; Check for both conditions
import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def takeSum ( a , n , m ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT sum += a [ i ] [ j ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def checkIndex ( n , m , a ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT if ( isPrime ( i + j ) ) : NEW_LINE INDENT if ( isPrime ( a [ i ] [ j ] ) != True ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True NEW_LINE DEDENT 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 = takeSum ( a , n , m ) NEW_LINE if ( isPrime ( sum ) and checkIndex ( n , m , a ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT