Count twin prime pairs in an Array | Python 3 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
from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( sqrt ( n ) ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def twinPrime ( n1 , n2 ) : NEW_LINE INDENT return ( isPrime ( n1 ) and isPrime ( n2 ) and abs ( n1 - n2 ) == 2 ) NEW_LINE DEDENT def countTwinPairs ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( twinPrime ( arr [ i ] , arr [ j ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countTwinPairs ( arr , n ) ) NEW_LINE DEDENT