Count prime pairs whose difference is also a Prime Number | Python3 program to implement the above approach ; Function to find all prime numbers in the range [ 1 , N ] ; isPrime [ i ] : Stores if i is a prime number or not ; Calculate all prime numbers up to Max using Sieve of Eratosthenes ; If P is a prime number ; Set all multiple of P as non - prime ; Update isPrime ; Function to count pairs of prime numbers in the range [ 1 , N ] whose difference is prime ; Function to count pairs of prime numbers whose difference is also a prime number ; isPrime [ i ] : Stores if i is a prime number or not ; Iterate over the range [ 2 , N ] ; If i and i - 2 is a prime number ; Update cntPairs ; Driver Code
from math import sqrt NEW_LINE def SieveOfEratosthenes ( N ) : NEW_LINE INDENT isPrime = [ True for i in range ( N + 1 ) ] NEW_LINE isPrime [ 0 ] = False NEW_LINE isPrime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( isPrime [ p ] ) : NEW_LINE INDENT for i in range ( p * p , N + 1 , p ) : NEW_LINE INDENT isPrime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT return isPrime NEW_LINE DEDENT def cntPairsdiffOfPrimeisPrime ( N ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE isPrime = SieveOfEratosthenes ( N ) NEW_LINE for i in range ( 2 , N + 1 , 1 ) : NEW_LINE INDENT if ( isPrime [ i ] and isPrime [ i - 2 ] ) : NEW_LINE INDENT cntPairs += 2 NEW_LINE DEDENT DEDENT return cntPairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE print ( cntPairsdiffOfPrimeisPrime ( N ) ) NEW_LINE DEDENT