Related Articles
Count prime pairs whose difference is also a Prime Number
• Last Updated : 23 Apr, 2021

Given an integer N, the task is to count the number of pairs of prime numbers in the range [1, N] such that the difference between elements of each pair is also a prime number.

Examples:

Input: N = 5
Output:
Explanations:
Pair of prime numbers in the range [1, 5] whose difference between elements is also a prime number are:
(2, 5) = 3 (Prime number)
(3, 5) = 2 (Prime number)
Therefore, the count of pairs of the prime numbers whose difference is also a prime number is 2.

Input: N = 11
Output: 4

Naive Approach: The simplest approach to solve this problem is to generate all possible pairs of the elements in the range [1, N] and for each pair, check if both the elements and the difference between both the elements of the pair is a prime number or not. If found to be true then increment the count. Finally, print the count.

Time Complexity: O(N2 * √N)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is based on the following observations:

Odd number – Even Number = Odd Number
Odd number – Odd number = Even number
2 is the only even prime number.
Therefore, the problem reduces to check only for those pairs of prime numbers whose difference between the elements of the pair is equal to 2.

Follow the steps below to solve the problem:

• Initialize a variable, say cntPairs to store the count of pairs of prime numbers such that the difference between elements of each pair is also a prime number.
• Initialize an array, say sieve[] to check if a number in the range [1, N] is a prime number or not.
• Find all the prime numbers in the range [1, N] using Sieve of Eratosthenes.
• Iterate over the range [2, N], and for each element in the given range, check if the sieve[i] and sieve[i – 2] are true or not. If found to be true then increment the value of cntPairs by 2.
• Finally, print the value of cntPairs.

Below is the implementation of the above approach:

## C++

 `// C++ program to implement``// the above approach` `#include ``using` `namespace` `std;` `// Function to find all prime``// numbers in the range [1, N]``vector<``bool``> SieveOfEratosthenes(``    ``int` `N)``{``  ` `    ``// isPrime[i]: Stores if i is``    ``// a prime number or not``    ``vector<``bool``> isPrime(N, ``true``);``  ` `    ``isPrime = ``false``;``    ``isPrime = ``false``;``  ` `    ``// Calculate all prime numbers up to``    ``// Max using Sieve of Eratosthenes``    ``for` `(``int` `p = 2; p * p <= N; p++) {``  ` `        ``// If P is a prime number``        ``if` `(isPrime[p]) {``  ` `            ``// Set all multiple of P``            ``// as non-prime``            ``for` `(``int` `i = p * p; i <= N;``                 ``i += p) {``  ` `                ``// Update isPrime``                ``isPrime[i] = ``false``;``            ``}``        ``}``    ``}``    ``return` `isPrime;``}` `// Function to count pairs of``// prime numbers in the range [1, N]``// whose difference is prime``int` `cntPairsdiffOfPrimeisPrime(``int` `N)``{``    ` `    ``// Function to count pairs of``    ``// prime numbers whose difference  ``    ``// is also a prime number``    ``int` `cntPairs = 0;``    ` `    ` `    ``// isPrime[i]: Stores if i is``    ``// a prime number or not``    ``vector<``bool``> isPrime``          ``= SieveOfEratosthenes(N);``    ` `    ``// Iterate over the range [2, N]``    ``for` `(``int` `i = 2; i <= N; i++) {``        ` `        ` `        ``// If i and i - 2 is``        ``// a prime number``        ``if` `(isPrime[i] &&``            ``isPrime[i - 2]) {``              ` `              ` `            ``// Update cntPairs``            ``cntPairs += 2;``        ``}``    ``}``    ``return` `cntPairs;``}` `// Driver Code``int` `main()``{``    ``int` `N = 5;``    ``cout << cntPairsdiffOfPrimeisPrime(N);``    ``return` `0;``}`

## Java

 `// Java program to implement``// the above approach``import` `java.util.*;` `class` `GFG{``    ` `// Function to find all prime``// numbers in the range [1, N]``public` `static` `boolean``[] SieveOfEratosthenes(``int` `N)``{``    ` `    ``// isPrime[i]: Stores if i is``    ``// a prime number or not``    ``boolean``[] isPrime = ``new` `boolean``[N + ``1``];``    ``Arrays.fill(isPrime, ``true``);` `    ``isPrime[``0``] = ``false``;``    ``isPrime[``1``] = ``false``;` `    ``// Calculate all prime numbers up to``    ``// Max using Sieve of Eratosthenes``    ``for``(``int` `p = ``2``; p * p <= N; p++)``    ``{``        ` `        ``// If P is a prime number``        ``if` `(isPrime[p])``        ``{``            ` `            ``// Set all multiple of P``            ``// as non-prime``            ``for``(``int` `i = p * p; i <= N; i += p)``            ``{``                ` `                ``// Update isPrime``                ``isPrime[i] = ``false``;``            ``}``        ``}``    ``}``    ``return` `isPrime;``}` `// Function to count pairs of``// prime numbers in the range [1, N]``// whose difference is prime``public` `static` `int` `cntPairsdiffOfPrimeisPrime(``int` `N)``{``    ` `    ``// Function to count pairs of``    ``// prime numbers whose difference``    ``// is also a prime number``    ``int` `cntPairs = ``0``;` `    ``// isPrime[i]: Stores if i is``    ``// a prime number or not``    ``boolean``[] isPrime = SieveOfEratosthenes(N);` `    ``// Iterate over the range [2, N]``    ``for``(``int` `i = ``2``; i <= N; i++)``    ``{``        ` `        ``// If i and i - 2 is``        ``// a prime number``        ``if` `(isPrime[i] && isPrime[i - ``2``])``        ``{``            ` `            ``// Update cntPairs``            ``cntPairs += ``2``;``        ``}``    ``}``    ``return` `cntPairs;``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ``int` `N = ``5``;``    ` `    ``System.out.println(cntPairsdiffOfPrimeisPrime(N));``}``}` `// This code is contributed by hemanth gadarla`

## Python3

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

## C#

 `// C# program to implement``// the above approach ``using` `System;`` ` `class` `GFG{``    ` `// Function to find all prime``// numbers in the range [1, N]``public` `static` `bool``[] SieveOfEratosthenes(``int` `N)``{``    ` `    ``// isPrime[i]: Stores if i is``    ``// a prime number or not``    ``bool``[] isPrime = ``new` `bool``[N + 1];``    ``for``(``int` `i = 0; i < N + 1; i++)``    ``{``        ``isPrime[i] = ``true``;``    ``}`` ` `    ``isPrime = ``false``;``    ``isPrime = ``false``;`` ` `    ``// Calculate all prime numbers up to``    ``// Max using Sieve of Eratosthenes``    ``for``(``int` `p = 2; p * p <= N; p++)``    ``{``        ` `        ``// If P is a prime number``        ``if` `(isPrime[p])``        ``{``            ` `            ``// Set all multiple of P``            ``// as non-prime``            ``for``(``int` `i = p * p; i <= N; i += p)``            ``{``                ` `                ``// Update isPrime``                ``isPrime[i] = ``false``;``            ``}``        ``}``    ``}``    ``return` `isPrime;``}`` ` `// Function to count pairs of``// prime numbers in the range [1, N]``// whose difference is prime``public` `static` `int` `cntPairsdiffOfPrimeisPrime(``int` `N)``{``    ` `    ``// Function to count pairs of``    ``// prime numbers whose difference``    ``// is also a prime number``    ``int` `cntPairs = 0;`` ` `    ``// isPrime[i]: Stores if i is``    ``// a prime number or not``    ``bool``[] isPrime = SieveOfEratosthenes(N);`` ` `    ``// Iterate over the range [2, N]``    ``for``(``int` `i = 2; i <= N; i++)``    ``{``        ` `        ``// If i and i - 2 is``        ``// a prime number``        ``if` `(isPrime[i] && isPrime[i - 2])``        ``{``            ` `            ``// Update cntPairs``            ``cntPairs += 2;``        ``}``    ``}``    ``return` `cntPairs;``}`` ` `// Driver Code``public` `static` `void` `Main()``{``    ``int` `N = 5;``     ` `    ``Console.WriteLine(cntPairsdiffOfPrimeisPrime(N));``}``}` `// This code is contributed by susmitakundugoaldanga`

## Javascript

 ``
Output:
`2`

Time Complexity: O(N * log(log(N)))
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up