Count prime numbers that can be expressed as sum of consecutive prime numbers

Given an integer N, the task is to find the number of prime numbers up to N that can be expressed as a sum of consecutive primes.

Examples:

Input: N = 45
Output: 3
Explanation:
Below are the prime numbers up to 45 that can be expressed as sum of consecutive prime numbers:

  • 5 = 2 + 3
  • 17 = 2 + 3 + 5 + 7
  • 41 = 2 + 3 + 5 + 7 + 11 + 13

Therefore, the count is 3. 

Input: N = 4
Output:



Approach: The idea is to use the Primality Test Algorithm. Using this, all primes not exceeding N can be found. After that, each number that can be expressed as consecutive primes can be found. Follow the steps below to solve the problem:

  1. Traverse through each number from 1 to N, checking if it is a prime and stored it in a vector.
  2. Sort all the stored prime numbers in the vector.
  3. Let there be X primes present in the vector. Initialize sum as the smallest prime found i.e., element at index 0 in the vector.
  4. Iterate over the range [1, X – 1] and add each element to the sum.
  5. After adding, check if the sum is a prime or not and the sum is less than N or not. If it found to be true, then increment the counter. Otherwise, if the sum becomes greater than N, break the loop.
  6. After all the above steps, print the count of prime numbers stored in the counter.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if a
// number is prime or not
int isprm(int n)
{
    // Base Case
    if (n <= 1)
        return 0;
    if (n <= 3)
        return 1;
    if (n % 2 == 0 || n % 3 == 0)
        return 0;
  
    // Iterate till [5, sqrt(N)] to
    // detect primality of numbers
    for (int i = 5;
         i * i <= n; i = i + 6) {
  
        // If N is divisible by i
        // or i + 2
        if (n % i == 0 || n % (i + 2) == 0)
            return 0;
    }
  
    // Return 1 if N is prime
    return 1;
}
  
// Function to count the prime numbers
// which can be expressed as sum of 
// consecutive prime numbers
int countprime(int n)
{
    // Initialize count as 0
    int count = 0;
  
    // Stores prime numbers
    vector<int> primevector;
  
    for (int i = 2; i <= n; i++) {
  
        // If i is prime
        if (isprm(i) == 1) {
            primevector.push_back(i);
        }
    }
  
    // Initialize the sum
    int sum = primevector[0];
  
    // Find all required primes upto N
    for (int i = 1;
         i < primevector.size(); i++) {
  
        // Add it to the sum
        sum += primevector[i];
        if (sum > n)
            break;
        if (isprm(sum) == 1) {
            count++;
        }
    }
  
    // Return the final count
    return count;
}
  
// Driver Code
int main()
{
    // Given number N
    int N = 45;
  
    // Function Call
    cout << countprime(N);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for 
// the above approach
import java.util.*;
class GFG{
  
// Function to check if a
// number is prime or not
static int isprm(int n)
{
  // Base Case
  if (n <= 1)
    return  0;
  if (n <= 3)
    return 1;
  if (n % 2 == 0 || 
      n % 3 == 0)
    return 0;
  
  // Iterate till [5, Math.sqrt(N)]
  // to detect primality of numbers
  for (int i = 5; i * i <= n; 
           i = i + 6
  {
    // If N is divisible by i
    // or i + 2
    if (n % i == 0 || 
        n % (i + 2) == 0)
      return 0;
  }
  
  // Return 1 if N is prime
  return 1;
}
  
// Function to count the prime numbers
// which can be expressed as sum of 
// consecutive prime numbers
static int countprime(int n)
{
  // Initialize count as 0
  int count = 0;
  
  // Stores prime numbers
  Vector<Integer> primevector = 
                  new Vector<>();
  
  for (int i = 2; i <= n; i++) 
  {
    // If i is prime
    if (isprm(i) == 1
    {
      primevector.add(i);
    }
  }
  
  // Initialize the sum
  int sum = primevector.elementAt(0);
  
  // Find all required primes upto N
  for (int i = 1
           i < primevector.size(); i++) 
  {
    // Add it to the sum
    sum += primevector.elementAt(i);
    if (sum > n)
      break;
    if (isprm(sum) == 1
    {
      count++;
    }
  }
  
  // Return the final count
  return count;
}
  
// Driver Code
public static void main(String[] args)
{
  // Given number N
  int N = 45;
  
  // Function Call
  System.out.print(countprime(N));
}
}
  
// This code is contributed by gauravrajput1

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
  
# Function to check if a
# number is prime or not
def isprm(n):
      
    # Base Case
    if (n <= 1):
        return 0
    if (n <= 3):
        return 1
    if (n % 2 == 0 or n % 3 == 0):
        return 0
  
    # Iterate till [5, sqrt(N)] to
    # detect primality of numbers
    i = 5
    while (i * i <= n):
  
        # If N is divisible by i
        # or i + 2
        if (n % i == 0 or 
            n % (i + 2) == 0):
            return 0
          
        i = i + 6
      
    # Return 1 if N is prime
    return 1
  
# Function to count the prime numbers
# which can be expressed as sum of 
# consecutive prime numbers
def countprime(n):
      
    # Initialize count as 0
    count = 0
  
    # Stores prime numbers
    primevector = []
  
    for i in range(2, n + 1):
  
        # If i is prime
        if (isprm(i) == 1):
            primevector.append(i)
          
    # Initialize the sum
    sum = primevector[0]
  
    # Find all required primes upto N
    for i in range(1, len(primevector)):
  
        # Add it to the sum
        sum += primevector[i]
        if (sum > n):
            break
        if (isprm(sum) == 1):
            count += 1
  
    # Return the final count
    return count
  
# Driver Code
  
# Given number N
N = 45
  
# Function call
print(countprime(N))
  
# This code is contributed by code_hunt

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for 
// the above approach
using System;
using System.Collections.Generic;
class GFG{
  
// Function to check if a
// number is prime or not
static int isprm(int n)
{
  // Base Case
  if (n <= 1)
    return  0;
  if (n <= 3)
    return 1;
  if (n % 2 == 0 || 
      n % 3 == 0)
    return 0;
  
  // Iterate till [5, Math.Sqrt(N)]
  // to detect primality of numbers
  for (int i = 5; i * i <= n; 
           i = i + 6) 
  {
    // If N is divisible by i
    // or i + 2
    if (n % i == 0 || 
        n % (i + 2) == 0)
      return 0;
  }
  
  // Return 1 if N is prime
  return 1;
}
  
// Function to count the prime numbers
// which can be expressed as sum of 
// consecutive prime numbers
static int countprime(int n)
{
  // Initialize count as 0
  int count = 0;
  
  // Stores prime numbers
  List<int> primevector = new List<int>();
  
  for (int i = 2; i <= n; i++) 
  {
    // If i is prime
    if (isprm(i) == 1) 
    {
      primevector.Add(i);
    }
  }
  
  // Initialize the sum
  int sum = primevector[0];
  
  // Find all required primes upto N
  for (int i = 1; i < primevector.Count; i++) 
  {
    // Add it to the sum
    sum += primevector[i];
    if (sum > n)
      break;
    if (isprm(sum) == 1) 
    {
      count++;
    }
  }
  
  // Return the readonly count
  return count;
}
  
// Driver Code
public static void Main(String[] args)
{
  // Given number N
  int N = 45;
  
  // Function Call
  Console.Write(countprime(N));
}
}
  
// This code is contributed by shikhasingrajput

chevron_right


Output: 

3

Time Complexity: O(N3/2)
Auxiliary Space: O(√N)

Efficient Approach: The above approach can be optimized by precomputing the prime numbers up to N using the Sieve of Eratosthenes.

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.