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: 2
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 <bits/stdc++.h>usingnamespacestd;// Function to find all prime// numbers in the range [1, N] vector<bool> SieveOfEratosthenes(     intN) {       // isPrime[i]: Stores if i is     // a prime number or not     vector<bool> isPrime(N, true);       isPrime[0] = false;     isPrime[1] = false;       // Calculate all prime numbers up to     // Max using Sieve of Eratosthenes     for(intp = 2; p * p <= N; p++) {           // If P is a prime number         if(isPrime[p]) {               // Set all multiple of P             // as non-prime             for(inti = p * p; i <= N;                  i += p) {                   // Update isPrime                 isPrime[i] = false;             }         }     }     returnisPrime; } // Function to count pairs of// prime numbers in the range [1, N] // whose difference is primeintcntPairsdiffOfPrimeisPrime(intN){        // Function to count pairs of     // prime numbers whose difference       // is also a prime number    intcntPairs = 0;            // isPrime[i]: Stores if i is     // a prime number or not     vector<bool> isPrime          = SieveOfEratosthenes(N);        // Iterate over the range [2, N]    for(inti = 2; i <= N; i++) {                        // If i and i - 2 is         // a prime number        if(isPrime[i] &&            isPrime[i - 2]) {                                        // Update cntPairs            cntPairs += 2;        }    }    returncntPairs;}// Driver Codeintmain(){    intN = 5;    cout << cntPairsdiffOfPrimeisPrime(N);    return0;} | 
Java
| // Java program to implement// the above approachimportjava.util.*;classGFG{    // Function to find all prime// numbers in the range [1, N]publicstaticboolean[] SieveOfEratosthenes(intN){        // isPrime[i]: Stores if i is    // a prime number or not    boolean[] isPrime = newboolean[N + 1];    Arrays.fill(isPrime, true);    isPrime[0] = false;    isPrime[1] = false;    // Calculate all prime numbers up to    // Max using Sieve of Eratosthenes    for(intp = 2; p * p <= N; p++)    {                // If P is a prime number        if(isPrime[p])        {                        // Set all multiple of P            // as non-prime            for(inti = p * p; i <= N; i += p)             {                                // Update isPrime                isPrime[i] = false;            }        }    }    returnisPrime;}// Function to count pairs of// prime numbers in the range [1, N]// whose difference is primepublicstaticintcntPairsdiffOfPrimeisPrime(intN){        // Function to count pairs of    // prime numbers whose difference    // is also a prime number    intcntPairs = 0;    // isPrime[i]: Stores if i is    // a prime number or not    boolean[] isPrime = SieveOfEratosthenes(N);    // Iterate over the range [2, N]    for(inti = 2; i <= N; i++)     {                // If i and i - 2 is        // a prime number        if(isPrime[i] && isPrime[i - 2])         {                        // Update cntPairs            cntPairs += 2;        }    }    returncntPairs;}// Driver Codepublicstaticvoidmain(String args[]){    intN = 5;        System.out.println(cntPairsdiffOfPrimeisPrime(N));}}// This code is contributed by hemanth gadarla | 
Python3
| # Python3 program to implement# the above approachfrommath importsqrt# Function to find all prime# numbers in the range [1, N] defSieveOfEratosthenes(N):        # isPrime[i]: Stores if i is     # a prime number or not     isPrime =[Truefori inrange(N +1)]       isPrime[0] =False    isPrime[1] =False      # Calculate all prime numbers up to     # Max using Sieve of Eratosthenes     forp inrange(2, int(sqrt(N)) +1, 1):                # If P is a prime number         if(isPrime[p]):                        # Set all multiple of P             # as non-prime             fori inrange(p *p, N +1, p):                                # Update isPrime                 isPrime[i] =False                    returnisPrime# Function to count pairs of# prime numbers in the range [1, N] # whose difference is primedefcntPairsdiffOfPrimeisPrime(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]    fori inrange(2, N +1, 1):                # If i and i - 2 is         # a prime number        if(isPrime[i] andisPrime[i -2]):                        # Update cntPairs            cntPairs +=2    returncntPairs# Driver Codeif__name__ =='__main__':        N =5        print(cntPairsdiffOfPrimeisPrime(N))# This code is contributed by ipg2016107 | 
C#
| // C# program to implement// the above approach  usingSystem; classGFG{    // Function to find all prime// numbers in the range [1, N]publicstaticbool[] SieveOfEratosthenes(intN){        // isPrime[i]: Stores if i is    // a prime number or not    bool[] isPrime = newbool[N + 1];    for(inti = 0; i < N + 1; i++)    {        isPrime[i] = true;    }     isPrime[0] = false;    isPrime[1] = false;     // Calculate all prime numbers up to    // Max using Sieve of Eratosthenes    for(intp = 2; p * p <= N; p++)    {                // If P is a prime number        if(isPrime[p])        {                        // Set all multiple of P            // as non-prime            for(inti = p * p; i <= N; i += p)             {                                // Update isPrime                isPrime[i] = false;            }        }    }    returnisPrime;} // Function to count pairs of// prime numbers in the range [1, N]// whose difference is primepublicstaticintcntPairsdiffOfPrimeisPrime(intN){        // Function to count pairs of    // prime numbers whose difference    // is also a prime number    intcntPairs = 0;     // isPrime[i]: Stores if i is    // a prime number or not    bool[] isPrime = SieveOfEratosthenes(N);     // Iterate over the range [2, N]    for(inti = 2; i <= N; i++)     {                // If i and i - 2 is        // a prime number        if(isPrime[i] && isPrime[i - 2])         {                        // Update cntPairs            cntPairs += 2;        }    }    returncntPairs;} // Driver CodepublicstaticvoidMain(){    intN = 5;         Console.WriteLine(cntPairsdiffOfPrimeisPrime(N));}}// This code is contributed by susmitakundugoaldanga | 
Javascript
| <script>// JavaScript program to implement// the above approach// Function to find all prime// numbers in the range [1, N]functionSieveOfEratosthenes(N){         // isPrime[i]: Stores if i is    // a prime number or not    let isPrime = [];    for(let i = 0; i < N + 1; i++)    {        isPrime[i] = true;    }     isPrime[0] = false;    isPrime[1] = false;     // Calculate all prime numbers up to    // Max using Sieve of Eratosthenes    for(let p = 2; p * p <= N; p++)    {                 // If P is a prime number        if(isPrime[p])        {                         // Set all multiple of P            // as non-prime            for(let i = p * p; i <= N; i += p)            {                                 // Update isPrime                isPrime[i] = false;            }        }    }    returnisPrime;} // Function to count pairs of// prime numbers in the range [1, N]// whose difference is primefunctioncntPairsdiffOfPrimeisPrime(N){         // Function to count pairs of    // prime numbers whose difference    // is also a prime number    let cntPairs = 0;     // isPrime[i]: Stores if i is    // a prime number or not    let isPrime = SieveOfEratosthenes(N);     // Iterate over the range [2, N]    for(let i = 2; i <= N; i++)    {                 // If i and i - 2 is        // a prime number        if(isPrime[i] && isPrime[i - 2])        {                         // Update cntPairs            cntPairs += 2;        }    }    returncntPairs;}// Driver Code    let N = 5;         document.write(cntPairsdiffOfPrimeisPrime(N));     </script> | 
2
Time Complexity: O(N * log(log(N))) 
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







