Count twin prime pairs in an Array | Java program to count Twin Prime pairs in array ; A utility function to check if the number n is prime or not ; Base Cases ; Check to skip middle five numbers in below loop ; If n is divisible by i and i + 2 then it is not prime ; A utility function that check if n1 and n2 are Twin Primes or not ; Function to find Twin Prime pairs from the given array ; Iterate through all pairs ; Increment count if twin prime pair ; Driver 's code ; Function call to find Twin Primes pair
import java . util . * ; class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i += 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) { return false ; } } return true ; } static boolean twinPrime ( int n1 , int n2 ) { return ( isPrime ( n1 ) && isPrime ( n2 ) && Math . abs ( n1 - n2 ) == 2 ) ; } static int countTwinPairs ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( twinPrime ( arr [ i ] , arr [ j ] ) ) { count ++ ; } } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 5 , 11 } ; int n = arr . length ; System . out . print ( countTwinPairs ( arr , n ) ) ; } }