Count prime numbers up to N that can be represented as a sum of two prime numbers

Given a positive integer N, the task is to find the count of prime numbers less than or equal to N that can be represented as a sum of two prime numbers.
Examples:
Input: N = 6
Output: 1
Explanation:
5 is the only prime number over the range [1, 6] that can be represented as sum of 2 prime numbers i.e., 5 = 2 + 3, where 2, 3 and 5 are all primes.
Therefore, the count is 2.Input: N = 14
Output: 3
Naive Approach: The simplest approach to solve the given problem is to consider all possible pairs (i, j) over the range [1, N] and if i and j are prime numbers and (i + j) lies in the range [1, N] then increment the count of prime numbers. After checking for all possible pairs, print the value of the total count obtained.Â
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized based on the following observation:
- Apart from 2, all the prime numbers are odd
- It is not possible to represent a prime number(which is odd) to be represented as a sum of two odd prime numbers, so one of the two prime numbers should be 2.
- So for a prime number X to be a sum of two prime numbers, X – 2 must also be prime.
Follow the steps below to solve the problem:
- Initialize an array, say prime[] of size 105, and populate all the prime numbers till 105 using the Sieve Of Eratosthenes.
- Initialize an auxiliary array dp[] of the size (N + 1) where dp[i] is the count of prime numbers less than or equal to i that can be represented as a sum of 2 prime numbers.
- Iterate over the range [2, N] using the variable i and perform the following steps:
- Update the value of dp[i – 1] as the sum of dp[i – 1] and dp[i].
- Check if prime[i] and prime[i – 2] is true, then increment the value of dp[i] by 1.
- After completing the above steps, print the value of dp[N] as the resultant count.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to store all prime numbers// up to N using Sieve of Eratosthenesvoid SieveOfEratosthenes(    int n, bool prime[]){    // Set 0 and 1 as non-prime    prime[0] = 0;    prime[1] = 0;Â
    for (int p = 2; p * p <= n; p++) {Â
        // If p is prime        if (prime[p] == true) {Â
            // Set all multiples            // of p as non-prime            for (int i = p * p;                 i <= n; i += p) {                prime[i] = false;            }        }    }}Â
// Function to count prime numbers// up to N that can be represented// as the sum of two prime numbersvoid countPrime(int n){    // Stores all the prime numbers    bool prime[n + 1];    memset(prime, true, sizeof(prime));Â
    // Update the prime array    SieveOfEratosthenes(n, prime);Â
    // Create a dp array of size n + 1    int dp[n + 1];Â
    memset(dp, 0, sizeof(dp));Â
    // Update dp[1] = 0    dp[1] = 0;Â
    // Iterate over the range [2, N]    for (int i = 2; i <= n; i++) {Â
        // Add the previous count value        dp[i] += dp[i - 1];Â
        // Increment dp[i] by 1 if i        // and (i - 2) are both prime        if (prime[i] == 1            && prime[i - 2] == 1) {            dp[i]++;        }    }Â
    // Print the result    cout << dp[n];}Â
// Driver Codeint main(){Â Â Â Â int N = 6;Â Â Â Â countPrime(N);Â
    return 0;} |
Java
// Java approach for the above approachimport java.io.*;public class GFG{     // Function to store all prime numbers// up to N using Sieve of Eratosthenesstatic void SieveOfEratosthenes(int n, boolean prime[]){         // Set 0 and 1 as non-prime    prime[0] = false;    prime[1] = false;Â
    for(int p = 2; p * p <= n; p++)    {                 // If p is prime        if (prime[p] == true)        {                         // Set all multiples            // of p as non-prime            for(int i = p * p; i <= n; i += p)             {                prime[i] = false;            }        }    }}Â
// Function to count prime numbers// up to N that can be represented// as the sum of two prime numbersstatic void countPrime(int n){         // Stores all the prime numbers    boolean prime[] = new boolean[n + 1];Â
    for(int i = 0; i < prime.length; i++)    {        prime[i] = true;    }Â
    // Update the prime array    SieveOfEratosthenes(n, prime);Â
    // Create a dp array of size n + 1    int dp[] = new int[n + 1];    for(int i = 0; i < dp.length; i++)     {        dp[i] = 0;    }Â
    // Update dp[1] = 0    dp[1] = 0;Â
    // Iterate over the range [2, N]    for(int i = 2; i <= n; i++)     {                 // Add the previous count value        dp[i] += dp[i - 1];Â
        // Increment dp[i] by 1 if i        // and (i - 2) are both prime        if (prime[i] == true &&             prime[i - 2] == true)         {            dp[i]++;        }    }Â
    // Print the result    System.out.print(dp[n]);}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int N = 6;Â Â Â Â Â Â Â Â Â countPrime(N);}}Â
// This code is contributed by abhinavjain194 |
Python3
# Python3 program for the above approachÂ
# Function to store all prime numbers# up to N using Sieve of Eratosthenesdef SieveOfEratosthenes(n, prime):Â
    # Set 0 and 1 as non-prime    prime[0] = 0    prime[1] = 0Â
    p = 2         while p * p <= n:Â
        # If p is prime        if (prime[p] == True):Â
            # Set all multiples            # of p as non-prime            for i in range(p * p, n + 1, p):                prime[i] = FalseÂ
        p += 1Â
# Function to count prime numbers# up to N that can be represented# as the sum of two prime numbersdef countPrime(n):Â
    # Stores all the prime numbers    prime = [True] * (n + 1)Â
    # Update the prime array    SieveOfEratosthenes(n, prime)Â
    # Create a dp array of size n + 1    dp = [0] * (n + 1)Â
    # Update dp[1] = 0    dp[1] = 0Â
    # Iterate over the range [2, N]    for i in range(2, n + 1):Â
        # Add the previous count value        dp[i] += dp[i - 1]Â
        # Increment dp[i] by 1 if i        # and (i - 2) are both prime        if (prime[i] == 1 and prime[i - 2] == 1):            dp[i] += 1Â
    # Print the result    print(dp[n])Â
# Driver Codeif __name__ == "__main__":Â
    N = 6         countPrime(N)     # This code is contributed by mohit ukasp |
C#
// C# program for the above approachusing System;Â
class GFG{     // Function to store all prime numbers// up to N using Sieve of Eratosthenesstatic void SieveOfEratosthenes(int n, bool[] prime){         // Set 0 and 1 as non-prime    prime[0] = false;    prime[1] = false;Â
    for(int p = 2; p * p <= n; p++)    {                 // If p is prime        if (prime[p] == true)         {                         // Set all multiples            // of p as non-prime            for(int i = p * p; i <= n; i += p)            {                prime[i] = false;            }        }    }}Â
// Function to count prime numbers// up to N that can be represented// as the sum of two prime numbersstatic void countPrime(int n){         // Stores all the prime numbers    bool[] prime = new bool[n + 1];Â
    for(int i = 0; i < prime.Length; i++)    {        prime[i] = true;    }Â
    // Update the prime array    SieveOfEratosthenes(n, prime);Â
    // Create a dp array of size n + 1    int[] dp = new int[n + 1];    for(int i = 0; i < dp.Length; i++)     {        dp[i] = 0;    }Â
    // Update dp[1] = 0    dp[1] = 0;Â
    // Iterate over the range [2, N]    for(int i = 2; i <= n; i++)     {                 // Add the previous count value        dp[i] += dp[i - 1];Â
        // Increment dp[i] by 1 if i        // and (i - 2) are both prime        if (prime[i] == true &&             prime[i - 2] == true)         {            dp[i]++;        }    }Â
    // Print the result    Console.Write(dp[n]);}Â
// Driver codestatic void Main(){Â Â Â Â int N = 6;Â Â Â Â Â Â Â Â Â countPrime(N);}}Â
// This code is contributed by abhinavjain194 |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to store all prime numbers// up to N using Sieve of Eratosthenesfunction SieveOfEratosthenes(n, prime){         // Set 0 and 1 as non-prime    prime[0] = 0;    prime[1] = 0;Â
    for(var p = 2; p * p <= n; p++)    {                 // If p is prime        if (prime[p] == Boolean(true))        {                         // Set all multiples            // of p as non-prime            for(var i = p * p;i <= n; i += p)            {                prime[i] = Boolean(false);            }        }    }}Â
// Function to count prime numbers// up to N that can be represented// as the sum of two prime numbersfunction countPrime(n){         // Stores all the prime numbers    var prime = new Array(n + 1);    var x = new Boolean(true);    prime.fill(x);         // Update the prime array    SieveOfEratosthenes(n, prime);         // Create a dp array of size n + 1    var dp = new Array(n + 1);    dp.fill(0);         // Update dp[1] = 0    dp[1] = 0;         // Iterate over the range [2, N]    for(var i = 2; i <= n; i++)     {                 // Add the previous count value        dp[i] += dp[i - 1];                 // Increment dp[i] by 1 if i        // and (i - 2) are both prime        if (prime[i] == Boolean(true) &&             prime[i - 2] == Boolean(true))        {            dp[i]++;                 }    }         // Print the result    document.write(dp[n]);}Â
// Driver codevar n = 6;Â
countPrime(n);Â
// This code is contributed by SoumikMondalÂ
</script> |
1
Time Complexity: O(N * log(log(N)))
Auxiliary Space: O(N)
Approach:
Here is the code of above algorithm:
C++
#include <cmath>#include <iostream>#include <unordered_set>using namespace std;Â
// Function to check if a number is primebool isPrime(int n){    // If the number is less than or equal to    // 1, it is not prime    if (n <= 1) {Â
        return false;    }    // Loop to check for factors from 2 to the    // square root of the number    for (int i = 2; i <= sqrt(n); i++) {        // If the number is divisible by        // i, it is not prime        if (n % i == 0) {Â
            return false;        }    }    // If no factors found, the number is prime    return true;}Â
// Function to count prime numbers up to N that can be// represented as the sum of two prime numbersvoid countPrime(int n){ // Create an unordered set to    // store prime numbers    unordered_set<int> primes;    // Initialize a counter to keep track of    // the count of prime numbers that can be    // represented as sum of two primes    int count = 0;    // Loop to iterate from 2 to N    for (int i = 2; i <= n; i++) {        // Check if i is a prime number        if (isPrime(i)) {            // Add the prime number i to the set            primes.insert(i);            // Check if (i-2) is also a prime            // number and present in the set            if (primes.count(i - 2) > 0) {                // If yes, increment the count as                // (i-2) + 2 = i, which is a prime                // number represented as the sum of                // two primes                count++;            }        }    }    // Output the count of prime numbers that    // can be represented as the sum of two primes    cout << count << endl;}Â
// Driver codeint main(){ // Define the upper limit N    int N = 6;    // Call the function to count prime numbers up    // to N that can be represented as the sum of    // two prime numbers    countPrime(N);    return 0;} |
Java
import java.util.HashSet;import java.util.Set;Â
public class Main {Â
    // Function to check if a number is prime    public static boolean isPrime(int n) {        // If the number is less than or equal to 1, it is not prime        if (n <= 1) {            return false;        }        // Loop to check for factors from 2 to the square root of the number        for (int i = 2; i <= Math.sqrt(n); i++) {            // If the number is divisible by i, it is not prime            if (n % i == 0) {                return false;            }        }        // If no factors found, the number is prime        return true;    }Â
    // Function to count prime numbers up to N that can be represented as the sum of two prime numbers    public static void countPrime(int n) {        // Create a set to store prime numbers        Set<Integer> primes = new HashSet<>();        // Initialize a counter to keep track of the count of prime numbers that can be represented as the sum of two primes        int count = 0;        // Loop to iterate from 2 to N        for (int i = 2; i <= n; i++) {            // Check if i is a prime number            if (isPrime(i)) {                // Add the prime number i to the set                primes.add(i);                // Check if (i-2) is also a prime number and present in the set                if (primes.contains(i - 2)) {                    // If yes, increment the count as (i-2) + 2 = i, which is a prime number represented as the sum of two primes                    count++;                }            }        }        // Output the count of prime numbers that can be represented as the sum of two primes        System.out.println(count);    }Â
    // Driver code    public static void main(String[] args) {        // Define the upper limit N        int N = 6;        // Call the function to count prime numbers up to N that can be represented as the sum of two prime numbers        countPrime(N);    }} |
Python3
# Function to check if a number is primedef isPrime(n):    if n <= 1:        return False    for i in range(2, int(n**0.5) + 1):        if n % i == 0:            return False    return TrueÂ
# Function to count prime numbers# up to N that can be represented# as the sum of two prime numbersdef countPrime(n):    primes = set()    count = 0 #counts the prime numbers    for i in range(2, n+1):        if isPrime(i): #check if prime            primes.add(i)            if (i-2) in primes:                count += 1    print(count)Â
# Driver Codeif __name__ == "__main__":Â Â Â Â N = 6Â Â Â Â countPrime(N) |
C#
using System;using System.Collections.Generic;Â
namespace PrimeCount{    class GFG    {        // Function to check if a number is prime        static bool IsPrime(int n)        {            // If the number is less than or equal to            // 1, it is not prime            if (n <= 1)            {                return false;            }            // Loop to check for factors from 2 to the            // square root of the number            for (int i = 2; i <= Math.Sqrt(n); i++)            {                // If the number is divisible by                // i, it is not prime                if (n % i == 0)                {                    return false;                }            }            // If no factors found, the number is prime            return true;        }Â
        // Function to count prime numbers up to N that can be        // represented as the sum of two prime numbers        static void CountPrime(int n)        {            // Create a HashSet to store prime numbers            HashSet<int> primes = new HashSet<int>();            // Initialize a counter to keep track of            // the count of prime numbers that can be            // represented as the sum of two primes            int count = 0;            // Loop to iterate from 2 to N            for (int i = 2; i <= n; i++)            {                // Check if i is a prime number                if (IsPrime(i))                {                    // Add the prime number i to the set                    primes.Add(i);                    // Check if (i-2) is also a prime                    // number and present in the set                    if (primes.Contains(i - 2))                    {                        // If yes, increment the count as                        // (i-2) + 2 = i, which is a prime                        // number represented as the sum of                        // two primes                        count++;                    }                }            }            // Output the count of prime numbers that            // can be represented as the sum of two primes            Console.WriteLine(count);        }Â
        // Driver code        static void Main(string[] args)        {            // Define the upper limit N            int N = 6;            // Call the function to count prime numbers up            // to N that can be represented as the sum of            // two prime numbers            CountPrime(N);        }    }} |
Javascript
// Function to check if a number is primefunction isPrime(n) {    // If the number is less than or equal to 1, it is not prime    if (n <= 1) {        return false;    }Â
    // Loop to check for factors from 2 to the square root of the number    for (let i = 2; i <= Math.sqrt(n); i++) {        // If the number is divisible by i, it is not prime        if (n % i === 0) {            return false;        }    }Â
    // If no factors found, the number is prime    return true;}Â
// Function to count prime numbers up to N that can be represented as the sum of two prime numbersfunction countPrime(n) {    // Create a Set to store prime numbers    const primes = new Set();         // Initialize a counter to keep track of the count     // of prime numbers that can be represented as the sum of two primes    let count = 0;         // Loop to iterate from 2 to N    for (let i = 2; i <= n; i++) {        // Check if i is a prime number        if (isPrime(i)) {            // Add the prime number i to the Set            primes.add(i);                         // Check if (i-2) is also a prime number and present in the Set            if (primes.has(i - 2)) {                // If yes, increment the count as (i-2) + 2 = i, which is a prime                 // number represented as the sum of two primes                count++;            }        }    }         // Output the count of prime numbers that can be represented as the sum of two primes    console.log(count);}Â
// Driver codeconst N = 6; // Define the upper limit N// Call the function to count prime numbers up to N that can be represented// as the sum of two prime numberscountPrime(N); |
1
Time Complexity: O(n^(3/2))
Auxiliary Space: O(sqrt(n))
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



