Segmented Sieve (Print Primes in a Range)

Given a range [low, high], print all primes in this range? For example, if the given range is [10, 20], then output is 11, 13, 17, 19.

A Naive approach is to run a loop from low to high and check each number for primeness. 
A Better Approach is to precalculate primes up to the maximum limit using Sieve of Eratosthenes, then print all prime numbers in range. 
The above approach looks good, but consider the input range [50000, 55000]. the above Sieve approach would precalculate primes from 2 to 50100. This causes a waste of memory as well as time. Below is the Segmented Sieve based approach.

Segmented Sieve (Background) 
Below are basic steps to get an idea of how Segmented Sieve works 

  1. Use Simple Sieve to find all primes up to a predefined limit (square root of ‘high’ is used in below code) and store these primes in an array “prime[]”. Basically we call Simple Sieve for a limit and we not only find prime numbers, but also puts them in a separate array prime[].
  2. Create an array mark[high-low+1]. Here we need only O(n) space where n is number of elements in given range.
  3. Iterate through all primes found in step 1. For every prime, mark its multiples in given range [low..high].

So unlike simple sieve, we don’t check for all multiples of every number smaller than square root of high, we only check for multiples of primes found in step 1. And we don’t need O(high) space, we need O(sqrt(high) + n) space.
Below is the implementation of above idea.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to
// print all primes in a range
// using concept of Segmented Sieve
#include <bits/stdc++.h>
using namespace std;
 
// This functions finds all
// primes smaller than limit
// using simple sieve of eratosthenes. 
// It stores found
// primes in vector prime[]
void simpleSieve(int limit, vector<int>& prime)
{
    bool mark[limit + 1];
    memset(mark, false, sizeof(mark));
 
    for (int i = 2; i*i <= limit; ++i)
    {
        if (mark[i] == false)
        {
            // If not marked yet, then its a prime
            prime.push_back(i);
            for (int j = i; j <= limit; j += i)
                mark[j] = true;
        }
    }
}
 
// Finds all prime numbers
// in given range using
// segmented sieve
void primesInRange(int low, int high)
{
     
    // Compute all primes smaller or equal to
    // square root of high using simple sieve
    int limit = floor(sqrt(high)) + 1;
    vector<int> prime;
    simpleSieve(limit, prime);
 
    // Count of elements in given range
    int n = high - low + 1;
 
    // Declaring boolean only for [low, high]
    bool mark[n + 1];
    memset(mark, false, sizeof(mark));
 
    // Use the found primes by
    // simpleSieve() to find
    // primes in given range
    for (int i = 0; i < prime.size(); i++)
    {
         
        // Find the minimum number
        // in [low..high] that is
        // a multiple of prime[i]
        // (divisible by prime[i])
        int loLim = floor(low / prime[i]) * prime[i];
        if (loLim < low)
            loLim += prime[i];
        if(loLim==prime[i])
            loLim += prime[i];
         
      /*  Mark multiples of prime[i]
          in [low..high]:
          We are marking j - low
          for j, i.e. each number
          in range [low, high] is
          mapped to [0, high - low]
          so if range is [50, 100] 
          marking 50 corresponds
          to marking 0, marking
          51 corresponds to 1 and
          so on.Also if the current j
          is prime don't mark
          it as true.In this way we need
          to allocate space only
          for range  */
        for (int j = loLim; j <= high; j += prime[i])
            if(j != prime[i])
              mark[j - low] = true;
    }
 
    // Numbers which are not marked
    // in range, are prime
    for (int i = low; i <= high; i++)
        if (!mark[i - low])
            cout << i << "  ";
}
 
// Driver Code
int main()
{
    int low = 10, high = 20;
    primesInRange(low, high);
    return 0;
}

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to print
# print all primes in a range
# using concept of Segmented Sieve
from math import floor, sqrt
 
# This functions finds
# all primes smaller than limit
# using simple sieve of eratosthenes.
# It stores found
# primes in list prime[]
 
 
def simpleSieve(limit, primes):
    mark = [False]*(limit+1)
 
    for i in range(2, limit+1):
        if not mark[i]:
 
            # If not marked yet,
            # then its a prime
            primes.append(i)
            for j in range(i, limit+1, i):
                mark[j] = True
 
 
# Finds all prime numbers
# in given range using
# segmented sieve
def primesInRange(low, high):
 
    # Comput all primes smaller
    # or equal to
    # square root of high
    # using simple sieve
    limit = floor(sqrt(high)) + 1
    primes = list()
    simpleSieve(limit, primes)
 
    # Count of elements in given range
    n = high - low + 1
 
    # Declaring boolean only for
    # [low, high]
    mark = [False]*(n+1)
 
    # Use the found primes by
    # simpleSieve() to find
    # primes in given range
    for i in range(len(primes)):
 
        # Find the minimum number
        # in [low..high] that is
        # a multiple of prime[i]
        # (divisible by prime[i])
        loLim = floor(low/primes[i]) * primes[i]
        if loLim < low:
            loLim += primes[i]
        if loLim == primes[i]:
            loLim += primes[i]
 
        # Mark multiples of primes[i]
        # in [low..high]:
        # We are marking j - low for j,
        # i.e. each number
        # in range [low, high] is mapped
        # to [0, high-low]
        # so if range is [50, 100]
        # marking 50 corresponds
        # to marking 0, marking 51
        # corresponds to 1 and
        # so on. In this way we need
        # to allocate space
        # only for range
        for j in range(loLim, high+1, primes[i]):
            if j != primes[i]:
                mark[j-low] = True
 
    # Numbers which are not marked
    # in range, are prime
    for i in range(low, high+1):
        if not mark[i-low]:
            print(i, end=" ")
 
 
# Driver code
low = 10
high = 100
primesInRange(low, high)

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print
// all primes in a range
// using concept of Segmented Sieve
import java.io.*;
import java.util.*;
 
class GFG {
    // This function uses simple sieve of eratosthenes to
    // find primes upto sqrt(high)
    static void simpleSieve(int limit,
                            Vector<Integer> prime)
    {
        // bound is square root of "high"
        int bound = (int)Math.sqrt(limit);
 
        boolean[] mark = new boolean[bound + 1];
        for (int i = 0; i <= bound; i++)
            mark[i] = true;
 
        for (int i = 2; i * i <= bound; i++) {
            if (mark[i] == true) {
                for (int j = i * i; j <= bound; j += i)
                    mark[i] = false;
            }
        }
 
        // adding primes to vector
        for (int i = 2; i <= bound; i++) {
            if (mark[i] == true)
                prime.add(i);
        }
    }
 
    // Finds all prime numbers in range low to high
    // using the primes we obtained from
    // simple sieve
    static void segmentedSieve(int low, int high)
    {
        Vector<Integer> prime = new Vector<Integer>();
        simpleSieve(high, prime); // stores primes upto
                                  // sqrt(high) in prime
 
        boolean[] mark = new boolean[high - low + 1];
        for (int i = 0; i < mark.length; i++)
            mark[i] = true;
 
        for (int i = 0; i < prime.size(); i++) {
            // find minimum number in [low...high]
            // that is multiple of prime[i]
            int loLim = (low / prime.get(i)) * prime.get(i);
            // loLim += prime.get(i);
            if (loLim < low)
                loLim += prime.get(i);
            if (loLim == prime.get(i))
                loLim += prime.get(i);
 
            for (int j = loLim; j <= high;
                 j += prime.get(i)) {
                if (j != prime.get(i))
                    mark[j - low] = false;
            }
        }
 
        // print all primes in [low...high]
        for (int i = low; i <= high; i++) {
            if (mark[i - low] == true)
                System.out.print(i + " ");
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int low = 10, high = 100;
        segmentedSieve(low, high);
    }
}

chevron_right


Output

11  13  15  17  19  

Segmented Sieve (What if ‘high’ value of range is too high and range is also big) 
Consider a situation where given high value is so high that neither sqrt(high) nor O(high-low+1) can fit in memory. How to find prims in range. For this situation, we run step 1 (Simple Sieve) only for a limit that can fit in memory. Then we divide given range in different segments. For every segment, we run step 2 and 3 considering low and high as end points of current segment. We add primes of current segment to prime[] before running the next segment.
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

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

Article Tags :
Practice Tags :


13


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.