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 ; 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 print " Yes " ; Otherwise , print " No " ; Driver Code ; Function Call
var prime = Array ( 1000005 ) . fill ( true ) ; function SieveOfEratosthenes ( N ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( var p = 2 ; p * p <= N ; p ++ ) { if ( prime [ p ] == true ) { for ( var i = p * p ; i <= N ; i += p ) prime [ i ] = false ; } } } function checkElementsOnDiagonal ( M , N ) { var flag = 1 ; SieveOfEratosthenes ( 1000000 ) ; for ( var i = 0 ; i < N ; i ++ ) { flag &= ( prime [ M [ i ] [ i ] ] && prime [ M [ i ] [ N - 1 - i ] ] ) ; } if ( flag ) document . write ( " " ) ; else document . write ( " " ) ; } var M = [ [ 1 , 2 , 3 , 13 ] , [ 5 , 3 , 7 , 8 ] , [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 7 ] ] ; var N = M . length ; checkElementsOnDiagonal ( M , N ) ;