Open In App

Sum of the first N Prime numbers

Last Updated : 23 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer ‘n’, the task is to find the sum of first ‘n’ prime numbers.
 

First few prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, ……

Examples: 
 

Input: N = 4
Output: 17
2, 3, 5, 7 are first 4 prime numbers so their sum is equal to 17

Input: N = 40
Output: 3087

 

Approach:
 

  • Create a sieve which will help us to identify if the number is prime or not in O(1) time.
  • Run a loop starting from 1 until and unless we find n prime numbers.
  • Add all the prime numbers and neglect those which are not prime.
  • Then, display the sum of 1st N prime numbers.

Below is the implementation of the above solution 
 

C++




// C++ implementation of above solution
#include <bits/stdc++.h>
using namespace std;
#define MAX 10000
 
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
bool prime[MAX + 1];
void SieveOfEratosthenes()
{
    memset(prime, true, sizeof(prime));
 
    prime[1] = false;
 
    for (int p = 2; p * p <= MAX; p++) {
 
        // If prime[p] is not changed, then it is a prime
        if (prime[p] == true) {
 
            // Set all multiples of p to non-prime
            for (int i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
}
 
// find the sum of 1st N prime numbers
int solve(int n)
{
    // count of prime numbers
    int count = 0, num = 1;
 
    // sum of prime numbers
    long long int sum = 0;
 
    while (count < n) {
 
        // if the number is prime add it
        if (prime[num]) {
            sum += num;
 
            // increase the count
            count++;
        }
 
        // get to next number
        num++;
    }
    return sum;
}
 
// Driver code
int main()
{
    // create the sieve
    SieveOfEratosthenes();
 
    int n = 4;
 
    // find the value of 1st n prime numbers
    cout << "Sum of 1st N prime numbers are :" << solve(n);
 
    return 0;
}


Java




// Java implementation of above solution
public class Improve {
     
    final static double MAX = 10000 ;
    // Create a boolean array "prime[0..n]" and initialize
    // all entries it as true. A value in prime[i] will
    // finally be false if i is Not a prime, else true.
    static boolean prime[] = new boolean [(int) (MAX + 1.0)] ;
    static void SieveOfEratosthenes()
    {
          
        for(int i = 0; i <= MAX; i++)
            prime[i] = true ;
         
        prime[1] = false;
       
        for (int p = 2; p * p <= MAX; p++) {
       
            // If prime[p] is not changed, then it is a prime
            if (prime[p] == true) {
       
                // Set all multiples of p to non-prime
                for (int i = p * 2; i <= MAX; i += p)
                    prime[i] = false;
            }
        }
    }
       
    // find the sum of 1st N prime numbers
    static int solve(int n)
    {
        // count of prime numbers
        int count = 0, num = 1;
       
        // sum of prime numbers
        long sum = 0;
       
        while (count < n) {
       
            // if the number is prime add it
            if (prime[num]) {
                sum += num;
       
                // increase the count
                count++;
            }
       
            // get to next number
            num++;
        }
        return (int) sum;
    }
    // Driver code 
    public static void main(String args[])
    {
        // create the sieve
        SieveOfEratosthenes();
       
        int n = 4;
       
        // find the value of 1st n prime numbers
        System.out.println("Sum of 1st N prime numbers are :" + solve(n));
           
    }
    // This Code is contributed by ANKITRAI1
}


Python 3




# Python3 implementation of
# above solution
MAX = 10000
 
# Create a boolean array "prime[0..n]"
# and initialize all entries it as true.
# A value in prime[i] will finally be
# false if i is Not a prime, else true.
prime = [True for i in range(MAX + 1)]
def SieveOfEratosthenes():
 
    prime[1] = False
 
    for p in range(2, MAX + 1):
 
        # If prime[p] is not changed,
        # then it is a prime
        if (prime[p] == True):
             
            # Set all multiples of
            # p to non-prime
            i = p * 2
            while(i <= MAX):
                prime[i] = False
                i = i + p
         
# find the sum of 1st
# N prime numbers
def solve( n):
 
    # count of prime numbers
    count = 0
    num = 1
 
    # sum of prime numbers
    total = 0
 
    while (count < n):
 
        # if the number is prime add it
        if ( prime[num] ):
            total = total + num
 
            # increase the count
            count = count + 1
         
        # get to next number
        num = num + 1
     
    return total
 
# Driver code
# create the sieve
SieveOfEratosthenes()
 
n = 4
 
# find the value of 1st
# n prime numbers
print("Sum of 1st N prime " +
      "numbers are :", solve(n))
 
# This code is contributed by ash264


C#




//C# implementation of above solution
 
using System;
 
public class GFG{
     
     static double MAX = 10000 ;
    // Create a boolean array "prime[0..n]" and initialize
    // all entries it as true. A value in prime[i] will
    // finally be false if i is Not a prime, else true.
    static bool []prime = new bool [(int)(MAX + 1.0)] ;
    static void SieveOfEratosthenes()
    {
         
        for(int i = 0; i <= MAX; i++)
            prime[i] = true ;
         
        prime[1] = false;
         
        for (int p = 2; p * p <= MAX; p++) {
         
            // If prime[p] is not changed, then it is a prime
            if (prime[p] == true) {
         
                // Set all multiples of p to non-prime
                for (int i = p * 2; i <= MAX; i += p)
                    prime[i] = false;
            }
        }
    }
         
    // find the sum of 1st N prime numbers
    static int solve(int n)
    {
        // count of prime numbers
        int count = 0, num = 1;
         
        // sum of prime numbers
        long sum = 0;
         
        while (count < n) {
         
            // if the number is prime add it
            if (prime[num]) {
                sum += num;
         
                // increase the count
                count++;
            }
         
            // get to next number
            num++;
        }
        return (int) sum;
    }
    // Driver code
    static public void Main (){
        // create the sieve
        SieveOfEratosthenes();
        int n = 4;
        // find the value of 1st n prime numbers
        Console.WriteLine("Sum of 1st N prime numbers are :" + solve(n));
             
    }
// This Code is contributed by ajit.
}


Javascript




<script>
 
// javascript implementation of above solution
 
var MAX = 10000 ;
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
var prime = Array.from({length: parseInt( (MAX + 1.0))}, (_, i) => false);
function SieveOfEratosthenes()
{
      
    for(i = 0; i <= MAX; i++)
        prime[i] = true ;
     
    prime[1] = false;
   
    for (p = 2; p * p <= MAX; p++) {
   
        // If prime[p] is not changed, then it is a prime
        if (prime[p] == true) {
   
            // Set all multiples of p to non-prime
            for (i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
}
   
// find the sum of 1st N prime numbers
function solve(n)
{
    // count of prime numbers
    var count = 0, num = 1;
   
    // sum of prime numbers
    var sum = 0;
   
    while (count < n) {
   
        // if the number is prime add it
        if (prime[num]) {
            sum += num;
   
            // increase the count
            count++;
        }
   
        // get to next number
        num++;
    }
    return parseInt( sum);
}
// Driver code 
//create the sieve
SieveOfEratosthenes();
 
var n = 4;
 
// find the value of 1st n prime numbers
document.write("Sum of 1st N prime numbers are :" + solve(n));
 
// This code is contributed by 29AjayKumar
 
</script>


Output: 

Sum of 1st N prime numbers are :17

 

Note(For competitive programming): In a problem which contains a large number of queries, a vector can be used to store all the prime numbers in the range of 10^8, this will take extra O(N) space. We can also use prefix array to store the sum of first N prime numbers in the range of 10^8.
 



Similar Reads

Count numbers in a given range having prime and non-prime digits at prime and non-prime positions respectively
Given two integers L and R, the task is to find the count of numbers in the range [L, R] having prime digits at prime positions and non-prime digits at non-prime positions. Examples: Input: L = 5, R = 22 Output: 7Explanation: The numbers 6, 8, 9, 12, 13, 15, and 17 have prime digits at prime positions and non-prime digits at non-prime positions. In
15 min read
Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
Given an integer N, the task is to print N integers ? 109 such that no two consecutive of these integers are co-prime and every 3 consecutive are co-prime. Examples: Input: N = 3 Output: 6 15 10Input: N = 4 Output: 6 15 35 14 Approach: We can just multiply consecutive primes and for the last number just multiply the gcd(last, last-1) * 2. We do thi
22 min read
Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between sum of non-prime numbers and prime numbers. Note: 1 is neither prime nor non-prime. Examples: Input : 1 3 5 10 15 7 Output : 10 Explanation: Sum of non-primes = 25 Sum of primes = 15 Input : 3 4 6 7 Output : 0 Naive Approach: A simple solution is to travers
16 min read
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 = 45Output: 3Explanation:Below are the prime numbers up to 45 that can be expressed as sum of consecutive prime numbers: 5 = 2 + 317 = 2 + 3 + 5 + 741 = 2 + 3 + 5 + 7 + 11 + 13 Therefore, the count is
8 min read
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.There
16 min read
Permutation of first N positive integers such that prime numbers are at prime indices
Given an integer N, the task is to find the number of permutations of first N positive integers such that prime numbers are at prime indices (for 1-based indexing).Note: Since, the number of ways may be very large, return the answer modulo 109 + 7. Examples: Input: N = 3 Output: 2 Explanation: Possible permutation of first 3 positive integers, such
6 min read
Permutation of first N positive integers such that prime numbers are at prime indices | Set 2
Given an integer N, the task is to find the number of permutations of first N positive integers such that prime numbers are at prime indices (for 1-based indexing).Note: Since, the number of ways may be very large, return the answer modulo 109 + 7.Examples: Input: N = 3 Output: 2 Explanation: Possible permutation of first 3 positive integers, such
6 min read
Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between product of non-prime numbers and prime numbers.Note: 1 is neither prime nor non-prime.Examples: Input : arr[] = {1, 3, 5, 10, 15, 7} Output : 45 Explanation : Product of non-primes = 150 Product of primes = 105 Input : arr[] = {3, 4, 6, 7} Output : 3 Naive
15 min read
Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
Given an array arr[] of N positive integers, the task is to calculate the absolute difference between XOR of non-prime numbers and prime numbers. Note that 1 is neither prime nor composite.Examples: Input: arr[] = {1, 3, 5, 10, 15, 7} Output: 4 Xor of non-primes = 10 ^ 15 = 5 Xor of primes = 3 ^ 5 ^ 7 = 1 |5 - 1| = 4Input: arr[] = {3, 4, 6, 7} Outp
8 min read
Find prime factors of Z such that Z is product of all even numbers till N that are product of two distinct prime numbers
Given a number N (N &gt; 6), the task is to print the prime factorization of a number Z, where Z is the product of all numbers ≤ N that are even and can be expressed as the product of two distinct prime numbers. Example: Input: N = 6Output: 2→1 3→1Explanation: 6 is the only number ≤ N, which is even and a product of two distinct prime numbers (2 an
7 min read