Check if diagonal elements of a Matrix are Prime or not | Java program for the above approach ; 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
import java . io . * ; import java . util . * ; class GFG { static boolean [ ] prime = new boolean [ 1000005 ] ; static void SieveOfEratosthenes ( int N ) { Arrays . fill ( prime , true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= N ; i += p ) prime [ i ] = false ; } } } static void checkElementsOnDiagonal ( int [ ] [ ] M , int N ) { int flag = 1 ; SieveOfEratosthenes ( 1000000 ) ; for ( int i = 0 ; i < N ; i ++ ) { boolean flg = ( boolean ) ( prime [ M [ i ] [ i ] ] && prime [ M [ i ] [ N - 1 - i ] ] ) ; int val = ( flg ) ? 1 : 0 ; flag &= val ; } if ( flag != 0 ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } public static void main ( String [ ] args ) { int [ ] [ ] M = { { 1 , 2 , 3 , 13 } , { 5 , 3 , 7 , 8 } , { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 7 } } ; int N = M . length ; checkElementsOnDiagonal ( M , N ) ; } }