Open In App

Sum of all Primes in a given range using Sieve of Eratosthenes

Given a range [L, R]. The task is to find the sum of all the prime numbers in the given range from L to R both inclusive.

Examples:  

Input : L = 10, R = 20
Output : Sum = 60
Prime numbers between [10, 20] are:
11, 13, 17, 19
Therefore, sum = 11 + 13 + 17 + 19 = 60
Input : L = 15, R = 25
Output : Sum = 59

A Simple Solution is to traverse from L to R, check if the current number is prime. If yes, add it to . Finally, print the sum.
An Efficient Solution is to use Sieve of Eratosthenes to find all primes up to a given limit. Then, compute a prefix sum array to store sum till every value before the limit. Once we have prefix array, We just need to return prefix[R] – prefix[L-1].

Note: prefix[i] will store the sum of all prime numbers from 1 to 

Below is the implementation of the above approach: 

// CPP program to find sum of primes
// in range L to R
#include <bits/stdc++.h>
using namespace std;
 
const int MAX = 10000;
 
// prefix[i] is going to store sum of primes
// till i (including i).
int prefix[MAX + 1];
 
// Function to build the prefix sum array
void buildPrefix()
{
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    bool prime[MAX + 1];
    memset(prime, true, sizeof(prime));
 
    for (int p = 2; p * p <= MAX; p++) {
 
        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            for (int i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
 
    // Build prefix array
    prefix[0] = prefix[1] = 0;
    for (int p = 2; p <= MAX; p++) {
        prefix[p] = prefix[p - 1];
        if (prime[p])
            prefix[p] += p;
    }
}
 
// Function to return sum of prime in range
int sumPrimeRange(int L, int R)
{
    buildPrefix();
 
    return prefix[R] - prefix[L - 1];
}
 
// Driver code
int main()
{
    int L = 10, R = 20;
 
    cout << sumPrimeRange(L, R) << endl;
 
    return 0;
}

                    
// Java program to find sum of primes
// in range L to R
 
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG{
 
static final int MAX = 10000;
 
// prefix[i] is going to store sum of primes
// till i (including i).
static int prefix[]=new int[MAX + 1];
 
// Function to build the prefix sum array
static void buildPrefix()
{
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    boolean prime[] = new boolean[MAX + 1];
     
    for(int i = 0; i < MAX+1; i++)
    prime[i] = true;
 
    for (int p = 2; p * p <= MAX; p++) {
 
        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            for (int i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
 
    // Build prefix array
    prefix[0] = prefix[1] = 0;
    for (int p = 2; p <= MAX; p++) {
        prefix[p] = prefix[p - 1];
        if (prime[p] == true)
            prefix[p] += p;
    }
}
 
// Function to return sum of prime in range
static int sumPrimeRange(int L, int R)
{
    buildPrefix();
 
    return prefix[R] - prefix[L - 1];
}
 
// Driver code
public static void main(String args[])
{
    int L = 10, R = 20;
 
    System.out.println (sumPrimeRange(L, R));
 
}
}

                    
# Python 3 program to find sum of primes
# in range L to R
from math import sqrt
 
MAX = 10000
 
# prefix[i] is going to store sum of primes
# till i (including i).
prefix = [0 for i in range(MAX + 1)]
 
# Function to build the prefix sum array
def buildPrefix():
     
    # Create a boolean array "prime[0..n]". 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)]
 
    for p in range(2,int(sqrt(MAX)) + 1, 1):
         
        # If prime[p] is not changed, then
        # it is a prime
        if (prime[p] == True):
             
            # Update all multiples of p
            for i in range(p * 2, MAX + 1, p):
                prime[i] = False
 
    # Build prefix array
    prefix[0] = 0
    prefix[1] = 0
    for p in range(2, MAX + 1, 1):
        prefix[p] = prefix[p - 1]
        if (prime[p]):
            prefix[p] += p
 
# Function to return sum of prime in range
def sumPrimeRange(L, R):
    buildPrefix()
 
    return prefix[R] - prefix[L - 1]
 
# Driver code
if __name__ == '__main__':
    L = 10
    R = 20
    print(sumPrimeRange(L, R))
 
# This code is contributed by
# Surendra_Gangwar

                    
// C# program to find sum of
// primes in range L to R
using System;
class GFG
{
 
static int MAX = 10000;
 
// prefix[i] is going to
// store sum of primes
// till i (including i).
static int []prefix = new int[MAX + 1];
 
// Function to build the
// prefix sum array
static void buildPrefix()
{
    // Create a boolean array "prime[0..n]".
    // A value in prime[i] will finally
    // be false if i is Not a prime,
    // else true.
    bool []prime = new bool[MAX + 1];
     
    for(int i = 0; i < MAX+1; i++)
    prime[i] = true;
 
    for (int p = 2; p * p <= MAX; p++)
    {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
 
            // Update all multiples of p
            for (int i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
 
    // Build prefix array
    prefix[0] = prefix[1] = 0;
    for (int p = 2; p <= MAX; p++)
    {
        prefix[p] = prefix[p - 1];
        if (prime[p] == true)
            prefix[p] += p;
    }
}
 
// Function to return sum
// of prime in range
static int sumPrimeRange(int L, int R)
{
    buildPrefix();
 
    return prefix[R] - prefix[L - 1];
}
 
// Driver code
public static void Main()
{
    int L = 10, R = 20;
 
    Console.WriteLine(sumPrimeRange(L, R));
}
}
 
// This code is contributed
// by anuj_67

                    
<script>
// Jacascript program to find sum of primes
 
MAX = 10000;
 
// prefix[i] is going to store sum of primes
// till i (including i).
prefix = new Array(MAX + 1);
 
// Function to build the prefix sum array
function buildPrefix()
{
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    prime = new Array(MAX + 1);
    prime.fill(true);
 
    for (var p = 2; p * p <= MAX; p++) {
 
        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            for (var i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
 
    // Build prefix array
    prefix[0] = prefix[1] = 0;
    for (var p = 2; p <= MAX; p++) {
        prefix[p] = prefix[p - 1];
        if (prime[p])
            prefix[p] += p;
    }
}
 
// Function to return sum of prime in range
function sumPrimeRange(L, R)
{
    buildPrefix();
    return prefix[R] - prefix[L - 1];
}
 
var L = 10, R = 20;
document.write( sumPrimeRange(L, R) + "<br>");
 
// This code is contributed by SoumikMondal
</script>

                    

Output
60






Time and Space complexity will be as same as in Sieve Of Eratosthenes

Time Complexity: n*log(log(n)) (where n = MAX, because we are building sieve to that limit)

Auxiliary Space: O(n), since extra space taken is 10000.

Approach:  Here’s another approach to solve the problem using the Sieve of Eratosthenes 

Algorithm:

  1. Create a boolean array of size (R+1) to mark all numbers as prime initially. We will use the index of the array to represent the numbers. For example, index 2 represents the number 2, index 3 represents the number 3, and so on.
  2. Mark 0 and 1 as not prime since they are not prime numbers.
    For each index i from 2 to sqrt(R), if the number at index i is marked as prime, then mark all multiples of i as not prime and this can be done by iterating over all multiples of i and marking them as not prime in the boolean array.
  3. Iterate over the boolean array from index L to R, and if a number is marked as prime, add it to the sum.
  4. Return the sum as the output.
#include <iostream>
#include <vector>
#include <cmath>
 
using namespace std;
 
int sieve_of_eratosthenes_sum(int L, int R) {
    // Step 1
    vector<bool> is_prime(R + 1, true);
 
    // Step 2
    is_prime[0] = is_prime[1] = false;
 
    // Step 3
    for (int i = 2; i <= sqrt(R); i++) {
        if (is_prime[i]) {
            for (int j = i * i; j <= R; j += i) {
                is_prime[j] = false;
            }
        }
    }
 
    // Step 4
    int s = 0;
    for (int i = L; i <= R; i++) {
        if (is_prime[i]) {
            s += i;
        }
    }
 
    // Step 5
    return s;
}
 
int main() {
    // Example usage
    int L = 10;
    int R = 20;
    cout << sieve_of_eratosthenes_sum(L, R) << endl; // Output: 60
    return 0;
}

                    
public class Main {
    public static int sieveOfEratosthenesSum(int L, int R) {
        // Step 1
        boolean[] isPrime = new boolean[R + 1];
        for (int i = 0; i <= R; i++) {
            isPrime[i] = true;
        }
 
        // Step 2
        isPrime[0] = isPrime[1] = false;
 
        // Step 3
        for (int i = 2; i <= Math.sqrt(R); i++) {
            if (isPrime[i]) {
                for (int j = i * i; j <= R; j += i) {
                    isPrime[j] = false;
                }
            }
        }
 
        // Step 4
        int sum = 0;
        for (int i = L; i <= R; i++) {
            if (isPrime[i]) {
                sum += i;
            }
        }
 
        // Step 5
        return sum;
    }
 
    public static void main(String[] args) {
        int L = 10;
        int R = 20;
        System.out.println(sieveOfEratosthenesSum(L, R)); // Output: 60
    }
}

                    
import math
 
def sieve_of_eratosthenes_sum(L, R):
    # Step 1
    is_prime = [True] * (R+1)
     
    # Step 2
    is_prime[0] = is_prime[1] = False
     
    # Step 3
    for i in range(2, int(math.sqrt(R))+1):
        if is_prime[i]:
            for j in range(i*i, R+1, i):
                is_prime[j] = False
     
    # Step 4
    s = 0
    for i in range(L, R+1):
        if is_prime[i]:
            s += i
     
    # Step 5
    return s
 
# Example usage
L = 10
R = 20
print(sieve_of_eratosthenes_sum(L, R)) # Output: 60

                    
using System;
using System.Collections.Generic;
 
namespace SieveOfEratosthenes
{
    class Program
    {
        static int SieveOfEratosthenesSum(int L, int R)
        {
            // Step 1
            bool[] isPrime = new bool[R + 1];
            for (int i = 0; i <= R; i++)
            {
                isPrime[i] = true;
            }
 
            // Step 2
            isPrime[0] = isPrime[1] = false;
 
            // Step 3
            for (int i = 2; i <= Math.Sqrt(R); i++)
            {
                if (isPrime[i])
                {
                    for (int j = i * i; j <= R; j += i)
                    {
                        isPrime[j] = false;
                    }
                }
            }
 
            // Step 4
            int sum = 0;
            for (int i = L; i <= R; i++)
            {
                if (isPrime[i])
                {
                    sum += i;
                }
            }
 
            // Step 5
            return sum;
        }
 
        static void Main(string[] args)
        {
            // Example usage
            int L = 10;
            int R = 20;
            Console.WriteLine(SieveOfEratosthenesSum(L, R)); // Output: 60
        }
    }
}

                    
// Function to calculate the sum of prime numbers in the range [L, R]
function sieveOfEratosthenesSum(L, R) {
 
    const isPrime = new Array(R + 1).fill(true);
 
    // 0 and 1 are not prime numbers, so mark them as false.
    isPrime[0] = isPrime[1] = false;
 
    //Use the Sieve of Eratosthenes algorithm to find prime numbers.
    for (let i = 2; i <= Math.sqrt(R); i++) {
        if (isPrime[i]) {
            // Mark multiples of each prime number as non-prime.
            for (let j = i * i; j <= R; j += i) {
                isPrime[j] = false;
            }
        }
    }
 
    // Calculate the sum of prime numbers in the given range [L, R].
    let s = 0;
    for (let i = L; i <= R; i++) {
        if (isPrime[i]) {
            s += i;
        }
    }
    return s;
}
 
// Driver Code
const L = 10;
const R = 20;
console.log(sieveOfEratosthenesSum(L, R)); // Output: 60

                    

Output
60






Time Complexity:  O((R-L+1)log(log(R))) ,where R-L+1 is the range of numbers and log(log(R)) is the time complexity of the inner loop of the Sieve of Eratosthenes algorithm. This is because we are iterating over the range of numbers from L to R and performing the Sieve of Eratosthenes algorithm on this range to find the prime numbers. The time complexity of the Sieve of Eratosthenes algorithm is O(nlog(log(n))) where n is the maximum limit of the range of numbers. In our case, the maximum limit is R, so the time complexity of the Sieve of Eratosthenes algorithm is O(Rlog(log(R))). Since we are only performing the algorithm on a range of (R-L+1) numbers, the time complexity becomes O((R-L+1)log(log(R))).

Auxiliary Space: O(R+1), This is because we are storing a boolean value for each number in the range from 0 to R. In practice, this space requirement can be reduced by using a bit array instead of a boolean array to represent the numbers, which would reduce the space requirement to O(R/32) for a 32-bit system. However, the time complexity would remain the same.


Article Tags :