Tuesday, 19 Oct 2021

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

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 = 6Output: 1Explanation: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 = 14Output: 3Naive 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 oddIt 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++  #include using namespace std;  void SieveOfEratosthenes(    int n, bool prime[]){        prime = 0;    prime = 0;      for (int p = 2; p * p