Check if the Matrix follows the given constraints or not | Java implementation of the above approach ; 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
import java . util . * ; class GFG { static boolean [ ] prime ; static void buildSieve ( int sum ) { prime = new boolean [ sum + 1 ] ; Arrays . fill ( prime , true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p < ( sum + 1 ) ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i < ( sum + 1 ) ; i += p ) prime [ i ] = false ; } } } static int getSum ( int a [ ] [ ] ) { int s = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) for ( int j = 0 ; j < 5 ; j ++ ) s += a [ i ] [ j ] ; return s ; } static boolean checkIndex ( int n , int m , int a [ ] [ ] ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) { if ( prime [ i + j ] && ! prime [ a [ i ] [ j ] ] ) { return false ; } } return true ; } public static void main ( String [ ] args ) { int n = 4 , m = 5 ; int a [ ] [ ] = { { 1 , 2 , 3 , 2 , 2 } , { 2 , 2 , 7 , 7 , 7 } , { 7 , 7 , 21 , 7 , 10 } , { 2 , 2 , 3 , 6 , 7 } } ; int sum = getSum ( a ) ; buildSieve ( sum ) ; if ( prime [ sum ] && checkIndex ( n , m , a ) ) { System . out . print ( " YES " + "NEW_LINE"); } else System . out . print ( " NO " + "NEW_LINE"); } }