Open In App

Segmented Sieve (Print Primes in a Range)

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

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++




#include <bits/stdc++.h>
using namespace std;
// fillPrime function fills primes from 2 to sqrt of high in chprime(vector) array
void fillPrimes(vector<int>& prime, int high)
{
    bool ck[high + 1];
    memset(ck, true, sizeof(ck));
    ck[1] = false;
    ck[0] = false;
    for (int i = 2; (i * i) <= high; i++) {
        if (ck[i] == true) {
            for (int j = i * i; j <= sqrt(high); j = j + i) {
                ck[j] = false;
            }
        }
    }
    for (int i = 2; i * i <= high; i++) {
        if (ck[i] == true) {
            prime.push_back(i);
        }
    }
}
// in segmented sieve we check for prime from range [low, high]
void segmentedSieve(int low, int high)
{
    if (low<2 and high>=2){
        low = 2;
    }//for handling corner case when low = 1 and we all know 1 is not prime no.
    bool prime[high - low + 1];
  //here prime[0] indicates whether low is prime or not similarly prime[1] indicates whether low+1 is prime or not
    memset(prime, true, sizeof(prime));
 
    vector<int> chprime;
    fillPrimes(chprime, high);
    //chprimes has primes in range [2,sqrt(n)]
     // we take primes from 2 to sqrt[n] because the multiples of all primes below high are marked by these
   // primes in range 2 to sqrt[n] for eg: for number 7 its multiples i.e 14 is marked by 2, 21 is marked by 3,
   // 28 is marked by 4, 35 is marked by 5, 42 is marked 6, so 49 will be first marked by 7 so all number before 49
  // are marked by primes in range [2,sqrt(49)]
    for (int i : chprime) {
        int lower = (low / i);
        //here lower means the first multiple of prime which is in range [low,high]
        //for eg: 3's first multiple in range [28,40] is 30         
        if (lower <= 1) {
            lower = i + i;
        }
        else if (low % i) {
            lower = (lower * i) + i;
        }
        else {
            lower = (lower * i);
        }
        for (int j = lower; j <= high; j = j + i) {
            prime[j - low] = false;
        }
    }
   
    for (int i = low; i <= high; i++) {
        if (prime[i - low] == true) {
            cout << (i) << " ";
        }
    }
}
int main()
{
    // low should be greater than or equal to 2
    int low = 2;
    // low here is the lower limit
    int high = 100;
    // high here is the upper limit
      // in segmented sieve we calculate primes in range [low,high]
   // here we initially we find primes in range [2,sqrt(high)] to mark all their multiples as not prime
   //then we mark all their(primes) multiples in range [low,high] as false
   // this is a modified sieve of eratosthenes , in standard sieve of  eratosthenes we find prime from 1 to n(given number)
   // in segmented sieve we only find primes in a given interval
  cout<<"Primes in range "<<low<<" to "<< high<<" are\n";
    segmentedSieve(low, high);
}


Java




import java.util.*;
import java.lang.Math;
 
public class Main{
// fillPrime function fills primes from 2 to sqrt of high in chprime ArrayList   
    public static void fillPrime(ArrayList<Integer> chprime,int high)
    {
        boolean[] ck=new boolean[high+1];
        Arrays.fill(ck,true);
        ck[1]=false;
        ck[0]=false;
     
    for(int i=2;(i*i)<=high;i++)
    {
        if(ck[i]==true)
        {
            for(int j=i*i;j<=Math.sqrt(high);j=j+i)
            {
                ck[j]=false;
            }
        }
    }
    for(int i=2;i*i<=high;i++)
    {
        if(ck[i]==true)
        {
   //         cout<< i<<"\n";
           chprime.add(i);
        }
    }
}
// in segmented sieve we check for prime from range [low, high]
    public static void segmentedSieve(int low,int high)
    {
        ArrayList<Integer> chprime= new ArrayList<Integer>();
        fillPrime(chprime,high);
//chprimes has primes in range [2,sqrt(n)]
// we take primes from 2 to sqrt[n] because the multiples of all primes below high are marked by these
// primes in range 2 to sqrt[n] for eg: for number 7 its multiples i.e 14 is marked by 2, 21 is marked by 3,
// 28 is marked by 4, 35 is marked by 5, 42 is marked 6, so 49 will be first marked by 7 so all number before 49
// are marked by primes in range [2,sqrt(49)]        
         
        boolean[] prime=new boolean [high-low+1];
        Arrays.fill(prime,true);
//here prime[0] indicates whether low is prime or not similarly prime[1] indicates whether low+1 is prime or not       
        for(int i:chprime)
        {
            int lower=(low/i);
//here lower means the first multiple of prime which is in range [low,high]
//for eg: 3's first multiple in range [28,40] is 30 
            if(lower<=1)
            {
            lower=i+i;
            }
            else if(low%i!=0)
            {
            lower=(lower*i)+i;
            }
            else{
                lower=(lower*i);
            }
            for(int j=lower;j<=high;j=j+i)
            {
            prime[j-low]=false;
            }
        }
        for(int i=low;i<=high;i++)
        {
            if(prime[i-low]==true)
            {
            System.out.printf("%d ",i);
            }
        }    
    }
    public static void main(String[] args)
    {
// low should be greater than or equal to 2       
        int low=2;
// low here is the lower limit       
        int high=100;
// high here is the upper limit
// in segmented sieve we calculate primes in range [low,high]
// here we initially we find primes in range [2,sqrt(high)] to mark all their multiples as not prime
//then we mark all their(primes) multiples in range [low,high] as false
// this is a modified sieve of eratosthenes , in standard sieve of  eratosthenes we find prime from 1 to n(given number)
// in segmented sieve we only find primes in a given interval
        System.out.println("Primes in Range "+low+" to "+high+" are ");
        segmentedSieve(low,high);
    }
}


C#




// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler
 
using System;
using System.Collections;
using System.Collections.Generic;
 
public class main {
    // fillPrime function fills primes from 2 to sqrt of
    // high in chprime ArrayList
    public static void fillPrime(List<int> chprime,
                                 int high)
    {
        bool[] ck = new bool[high + 1];
        Array.Fill(ck, true);
        ck[1] = false;
        ck[0] = false;
 
        for (int i = 2; (i * i) <= high; i++) {
            if (ck[i] == true) {
                for (int j = i * i; j <= Math.Sqrt(high);
                     j = j + i) {
                    ck[j] = false;
                }
            }
        }
        for (int i = 2; i * i <= high; i++) {
            if (ck[i] == true) {
                //         cout<< i<<"\n";
                chprime.Add(i);
            }
        }
    }
    // in segmented sieve we check for prime from range
    // [low, high]
    public static void segmentedSieve(int low, int high)
    {
        List<int> chprime = new List<int>();
        fillPrime(chprime, high);
        // chprimes has primes in range [2,sqrt(n)]
        // we take primes from 2 to sqrt[n] because the
        // multiples of all primes below high are marked by
        // these primes in range 2 to sqrt[n] for eg: for
        // number 7 its multiples i.e 14 is marked by 2, 21
        // is marked by 3, 28 is marked by 4, 35 is marked
        // by 5, 42 is marked 6, so 49 will be first marked
        // by 7 so all number before 49 are marked by primes
        // in range [2,sqrt(49)]
 
        bool[] prime = new bool[high - low + 1];
        Array.Fill(prime, true);
        // here prime[0] indicates whether low is prime or
        // not similarly prime[1] indicates whether low+1 is
        // prime or not
        foreach(int i in chprime)
        {
            int lower = (low / i);
            // here lower means the first multiple of prime
            // which is in range [low,high] for eg: 3's first
            // multiple in range [28,40] is 30
            if (lower <= 1) {
                lower = i + i;
            }
            else if (low % i != 0) {
                lower = (lower * i) + i;
            }
            else {
                lower = (lower * i);
            }
            for (int j = lower; j <= high; j = j + i) {
                prime[j - low] = false;
            }
        }
        for (int i = low; i <= high; i++) {
            if (prime[i - low] == true) {
                Console.Write(i + " ");
            }
        }
    }
    public static void Main(string[] args)
    {
        // low should be greater than or equal to 2
        int low = 2;
        // low here is the lower limit
        int high = 100;
        // high here is the upper limit
        // in segmented sieve we calculate primes in range
        // [low,high] here we initially we find primes in
        // range [2,sqrt(high)] to mark all their multiples
        // as not prime
        // then we mark all their(primes) multiples in range
        // [low,high] as false
        // this is a modified sieve of eratosthenes , in
        // standard sieve of eratosthenes we find prime from
        // 1 to n(given number) in segmented sieve we only
        // find primes in a given interval
        Console.WriteLine("Primes in Range " + low + " to "
                          + high + " are ");
        segmentedSieve(low, high);
    }
}


Python




import math
 
# fillPrime function fills primes from 2 to sqrt of high in chprime list
def fillPrimes(chprime, high):
 
    ck = [True]*(high+1)
 
    l = int(math.sqrt(high))
    for i in range(2, l+1):
        if ck[i]:
            for j in range(i*i, l+1, i):
                ck[j] = False
                 
    for k in range(2, l+1):
        if ck[k]:
            chprime.append(k)
 
# in segmented sieve we check for prime from range [low, high]
def segmentedSieve(low, high):
     
    chprime = list()
    fillPrimes(chprime, high)
# chprimes has primes in range [2,sqrt(n)]
# we take primes from 2 to sqrt[n] because the multiples of all primes below high are marked by these
# primes in range 2 to sqrt[n] for eg: for number 7 its multiples i.e 14 is marked by 2, 21 is marked by 3,
# 28 is marked by 4, 35 is marked by 5, 42 is marked 6, so 49 will be first marked by 7 so all number before 49
# are marked by primes in range [2,sqrt(49)]
    prime = [True] * (high-low + 1)
# here prime[0] indicates whether low is prime or not similarly prime[1] indicates whether low+1 is prime or not
    for i in chprime:
        lower = (low//i)
# here lower means the first multiple of prime which is in range [low,high]
# for eg: 3's first multiple in range [28,40] is 30        
        if lower <= 1:
            lower = i+i
        elif (low % i) != 0:
            lower = (lower * i) + i
        else:
            lower = lower*i
        for j in range(lower, high+1, i):
            prime[j-low] = False
             
             
    for k in range(low, high + 1):
            if prime[k-low]:
                print(k, end=" ")
 
 
#DRIVER CODE
#   low should be greater than or equal to 2
low = 2
 
#  low here is the lower limit
high = 100
 
# high here is the upper limit
# in segmented sieve we calculate primes in range [low,high]
# here we initially we find primes in range [2,sqrt(high)] to mark all their multiples as not prime
# then we mark all their(primes) multiples in range [low,high] as false
# this is a modified sieve of eratosthenes , in standard sieve of  eratosthenes we find prime from 1 to n(given number)
# in segmented sieve we only find primes in a given interval
print("Primes in Range %d to %d are" )
segmentedSieve(low, high)


Go




package main
 
import "fmt"
 
const (
    maxN       = 10000
    filterSize = 101
)
 
var compositeFilter = make([]bool, filterSize)
var primesList = make([]int, 0)
 
func prepareSieve() {
    compositeFilter[0] = true
    compositeFilter[1] = true
    for p := 2; p*p < filterSize; p++ {
        if !compositeFilter[p] {
            for i := p * p; i < filterSize; i += p {
                compositeFilter[i] = true
            }
        }
    }
 
    for i, v := range compositeFilter {
        if !v {
            primesList = append(primesList, i)
        }
    }
 
}
 
func primesInRange(m, n int) {
    // we all know first prime starts at 2
    if m <= 1 {
        m = 2
    }
    d := (n - m) + 1
 
    composite := make([]bool, d)
    for _, p := range primesList {
        if p*p > n {
            break
        }
 
        i := (m / p) * p
 
        if i < m {
            i += p
        }
         
        // making sure we are not marking prime `p` as composite
        if i == p {
            i += p
        }
        // marking all the multiples of p as composite (except p itself)
        for ; i <= n; i += p {
            composite[i-m] = true
        }
    }
 
    for i := m; i <= n; i++ {
        if !composite[i-m] {
            fmt.Println(i)
        }
    }
}
 
 
func main() {
    prepareSieve()
    primesInRange(2, 100)
}


Javascript




// JS code to implement the approach
 
// fillPrime function fills primes from 2 to sqrt of high in
// chprime list
function fillPrimes(chprime, high)
{
 
    var ck = Array(high + 1).fill(true);
 
    var l = Math.sqrt(high);
    for (let i = 2; i <= l; i++) {
        if (ck[i]) {
            for (let j = i * i; j <= l; j += i) {
                ck[j] = false;
            }
        }
    }
    for (let k = 2; k <= l; k++) {
        if (ck[k]) {
            chprime.push(k);
        }
    }
}
 
// in segmented sieve we check for prime from range [low,
// high]
function segmentedSieve(low, high)
{
 
    var chprime = [];
    fillPrimes(chprime, high);
 
    // chprimes has primes in range [2,sqrt(n)]
    // we take primes from 2 to sqrt[n] because the
    // multiples of all primes below high are marked by
    // these
    // primes in range 2 to sqrt[n] for eg: for number 7 its
    // multiples i.e 14 is marked by 2, 21 is marked by 3,
    // 28 is marked by 4, 35 is marked by 5, 42 is marked 6,
    // so 49 will be first marked by 7 so all number before
    // 49
    // are marked by primes in range [2,sqrt(49)]
    var prime = Array(high - low + 1).fill(true);
    for (let i of chprime) {
        var lower = Math.floor(low / i);
        // here lower means the first multiple of prime
        // which is in range [low,high] for eg: 3's first
        // multiple in range [28,40] is 30
        if (lower <= 1) {
            lower = i + i;
        }
        else if ((low % i) != 0) {
            lower = (lower * i) + i;
        }
        else {
            lower = lower * i;
        }
        for (var j = lower; j <= high; j = j + i) {
            prime[j - low] = false;
        }
    }
 
    for (var i = low; i <= high; i++) {
        if (prime[i - low] == true) {
            process.stdout.write(i + " ");
        }
    }
}
 
// low should be greater than or equal to 2
var low = 2;
// low here is the lower limit
var high = 100;
// high here is the upper limit
// in segmented sieve we calculate primes in range
// [low,high]
// here we initially we find primes in range [2,sqrt(high)]
// to mark all their multiples as not prime
// then we mark all their(primes) multiples in range
// [low,high] as false
// this is a modified sieve of eratosthenes , in standard
// sieve of  eratosthenes we find prime from 1 to n(given
// number) in segmented sieve we only find primes in a given
// interval
process.stdout.write("Primes in range " + low + " to "
                     + high + " are\n");
segmentedSieve(low, high);
 
// This code is contributed by phaisng17


Output

Primes in range 2 to 100 are
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

Time Complexity : O(n)
Auxiliary Space: O(n)

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 primes 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.



Last Updated : 27 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads