Segmented Sieve (Print Primes in a Range)
Last Updated : 27 Jan, 2023
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
- 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[].
- Create an array mark[high-low+1]. Here we need only O(n) space where n is number of elements in given range.
- 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
OutputPrimes 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.
Similar Reads
Check for Prime Number Given a number n, check whether it is a prime number or not.Note: A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.Input: n = 7Output: trueExplanation: 7 is a prime number because it is greater than 1 and has no divisors other than 1 and itself.Input: n
11 min read
Primality Test Algorithms
Introduction to Primality Test and School MethodGiven a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}Examples : Input: n = 11Output: trueInput: n = 15Output: falseInput: n = 1Output:
10 min read
Fermat Method of Primality TestGiven a number n, check if it is prime or not. We have introduced and discussed the School method for primality testing in Set 1.Introduction to Primality Test and School MethodIn this post, Fermat's method is discussed. This method is a probabilistic method and is based on Fermat's Little Theorem.
10 min read
Primality Test | Set 3 (MillerâRabin)Given a number n, check if it is prime or not. We have introduced and discussed School and Fermat methods for primality testing.Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method)In this post, the Miller-Rabin method is discussed. This method is a probabili
15+ min read
Solovay-Strassen method of Primality TestWe have already been introduced to primality testing in the previous articles in this series. Introduction to Primality Test and School MethodFermat Method of Primality TestPrimality Test | Set 3 (MillerâRabin)The SolovayâStrassen test is a probabilistic algorithm used to check if a number is prime
13 min read
Lucas Primality TestA number p greater than one is prime if and only if the only divisors of p are 1 and p. First few prime numbers are 2, 3, 5, 7, 11, 13, ...The Lucas test is a primality test for a natural number n, it can test primality of any kind of number.It follows from Fermatâs Little Theorem: If p is prime and
12 min read
Sieve of Eratosthenes Given a number n, find all prime numbers less than or equal to n.Examples:Input: n = 10Output: [2, 3, 5, 7]Explanation: The prime numbers up to 10 obtained by Sieve of Eratosthenes are [2, 3, 5, 7].Input: n = 35Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]Explanation: The prime numbers up to 35 o
5 min read
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))? Pre-requisite: Sieve of Eratosthenes What is Sieve of Eratosthenes algorithm? In order to analyze it, let's take a number n and the task is to print the prime numbers less than n. Therefore, by definition of Sieve of Eratosthenes, for every prime number, it has to check the multiples of the prime an
3 min read
Sieve of Eratosthenes in 0(n) time complexity The classical Sieve of Eratosthenes algorithm takes O(N log (log N)) time to find all prime numbers less than N. In this article, a modified Sieve is discussed that works in O(N) time.Example : Given a number N, print all prime numbers smaller than N Input : int N = 15 Output : 2 3 5 7 11 13 Input :
12 min read
Programs and Problems based on Sieve of Eratosthenes
C++ Program for Sieve of EratosthenesGiven a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For example, if n is 10, the output should be "2, 3, 5, 7". If n is 20, the output should be "2, 3, 5, 7, 11, 13, 17, 19".CPP// C++ program to print all primes smaller than or equal to // n usin
2 min read
Java Program for Sieve of EratosthenesGiven a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For example, if n is 10, the output should be "2, 3, 5, 7". If n is 20, the output should be "2, 3, 5, 7, 11, 13, 17, 19". Java // Java program to print all primes smaller than or equal to // n
2 min read
Scala | Sieve of EratosthenesEratosthenes of Cyrene was a Greek mathematician, who discovered an amazing algorithm to find prime numbers. This article performs this algorithm in Scala. Step 1 : Creating an Int Stream Scala 1== def numberStream(n: Int): Stream[Int] = Stream.from(n) println(numberStream(10)) Output of above step
4 min read
Check if a number is Primorial Prime or notGiven a positive number N, the task is to check if N is a primorial prime number or not. Print 'YES' if N is a primorial prime number otherwise print 'NO.Primorial Prime: In Mathematics, A Primorial prime is a prime number of the form pn# + 1 or pn# - 1 , where pn# is the primorial of pn i.e the pro
10 min read
Sum of all Primes in a given range using Sieve of EratosthenesGiven 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 = 20Output : 60Explanation: Prime numbers between [10, 20] are: 11, 13, 17, 19Therefore, sum = 11 + 13 + 17 + 19 = 60Input : l = 15, r = 25Output : 59E
1 min read
Prime Factorization using Sieve O(log n) for multiple queriesWe can calculate the prime factorization of a number "n" in O(sqrt(n)) as discussed here. But O(sqrt n) method times out when we need to answer multiple queries regarding prime factorization.In this article, we study an efficient method to calculate the prime factorization using O(n) space and O(log
11 min read
Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given RangeA number which is divisible by 1 and itself or a number which has factors as 1 and the number itself is called a prime number. The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so. Example: Input : from = 1, to = 20 Out
3 min read
Segmented Sieve Given a number n, print all primes smaller than n. Input: N = 10Output: 2, 3, 5, 7Explanation : The output â2, 3, 5, 7â for input N = 10 represents the list of the prime numbers less than or equal to 10. Input: N = 5Output: 2, 3, 5 Explanation : The output â2, 3, 5â for input N = 5 represents the li
15+ min read
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 Sie
15 min read
Longest sub-array of Prime Numbers using Segmented Sieve Given an array arr[] of N integers, the task is to find the longest subarray where all numbers in that subarray are prime. Examples: Input: arr[] = {3, 5, 2, 66, 7, 11, 8} Output: 3 Explanation: Maximum contiguous prime number sequence is {2, 3, 5} Input: arr[] = {1, 2, 11, 32, 8, 9} Output: 2 Expla
13 min read
Sieve of Sundaram to print all primes smaller than n Given a number n, print all primes smaller than or equal to n.Examples: Input: n = 10Output: 2, 3, 5, 7Input: n = 20Output: 2, 3, 5, 7, 11, 13, 17, 19We have discussed Sieve of Eratosthenes algorithm for the above task. Below is Sieve of Sundaram algorithm.printPrimes(n)[Prints all prime numbers sma
10 min read