Count Sexy Prime Pairs in the given array | Java program to count Sexy Prime pairs in array ; To store check the prime number ; A utility function that find the Prime Numbers till N ; Resize the Prime Number ; Loop till Math . sqrt ( N ) to find prime numbers and make their multiple false in the bool array Prime ; Function that returns the count of SPP ( Sexy Prime Pair ) Pairs ; Find the maximum element in the given array arr [ ] ; Function to calculate the prime numbers till N ; To store the count of pairs ; To store the frequency of element in the array arr [ ] ; Sort before traversing the array ; Traverse the array and find the pairs with SPP ( Sexy Prime Pair ) ; If current element is Prime , then check for ( current element + 6 ) ; Return the count of pairs ; Driver code ; Function call to find SPP ( Sexy Prime Pair ) pair
import java . util . * ; class GFG { static boolean [ ] Prime ; static void computePrime ( int N ) { Prime = new boolean [ N + 1 ] ; Arrays . fill ( Prime , true ) ; Prime [ 0 ] = Prime [ 1 ] = false ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( Prime [ i ] ) { for ( int j = i * i ; j < N ; j += i ) { Prime [ j ] = false ; } } } } static int countSexyPairs ( int arr [ ] , int n ) { int maxE = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; computePrime ( maxE ) ; int count = 0 ; int freq [ ] = new int [ maxE + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( Prime [ arr [ i ] ] ) { if ( arr [ i ] + 6 < freq . length && freq [ arr [ i ] + 6 ] > 0 && Prime [ arr [ i ] + 6 ] ) { count ++ ; } } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 7 , 5 , 11 , 13 } ; int n = arr . length ; System . out . print ( countSexyPairs ( arr , n ) ) ; } }