Check if diagonal elements of a Matrix are Prime or not | Stores if a number is prime or not ; Function to generate and store primes using Sieve Of Eratosthenes ; Set all numbers as prime memset ( prime , true , sizeof ( prime ) ) ; If p is a prime ; Set all its multiples as non - prime ; Function to check if all diagonal elements are prime or not ; Stores if all diagonal elements are prime or not ; Precompute primes ; Traverse the range [ 0 , N - 1 ] ; Check if numbers on the cross diagonal and main diagonal are primes or not ; If true , then pr " Yes " ; Otherwise , pr " No " ; Driver Code ; Function Call
prime = [ True ] * 1000005 NEW_LINE def SieveOfEratosthenes ( N ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , N + 1 ) : NEW_LINE INDENT if p * p > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , N + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def checkElementsOnDiagonal ( M , N ) : NEW_LINE INDENT flag = 1 NEW_LINE SieveOfEratosthenes ( 1000000 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT flag &= ( prime [ M [ i ] [ i ] ] and prime [ M [ i ] [ N - 1 - i ] ] ) NEW_LINE DEDENT if ( flag ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = [ [ 1 , 2 , 3 , 13 ] , [ 5 , 3 , 7 , 8 ] , [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 7 ] ] NEW_LINE N = len ( M ) NEW_LINE checkElementsOnDiagonal ( M , N ) NEW_LINE DEDENT