Count prime pairs whose difference is also a Prime Number | 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
function SieveOfEratosthenes ( N ) { let isPrime = [ ] ; for ( let i = 0 ; i < N + 1 ; i ++ ) { isPrime [ i ] = true ; } isPrime [ 0 ] = false ; isPrime [ 1 ] = false ; for ( let p = 2 ; p * p <= N ; p ++ ) { if ( isPrime [ p ] ) { for ( let i = p * p ; i <= N ; i += p ) { isPrime [ i ] = false ; } } } return isPrime ; } function cntPairsdiffOfPrimeisPrime ( N ) { let cntPairs = 0 ; let isPrime = SieveOfEratosthenes ( N ) ; for ( let i = 2 ; i <= N ; i ++ ) { if ( isPrime [ i ] && isPrime [ i - 2 ] ) { cntPairs += 2 ; } } return cntPairs ; } let N = 5 ; document . write ( cntPairsdiffOfPrimeisPrime ( N ) ) ;