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
- 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;
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);
}
}
}
void segmentedSieve( int low, int high)
{
if (low<2 and high>=2){
low = 2;
}
bool prime[high - low + 1];
memset (prime, true , sizeof (prime));
vector< int > chprime;
fillPrimes(chprime, high);
for ( int i : chprime) {
int lower = (low / i);
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()
{
int low = 2;
int high = 100;
cout<< "Primes in range " <<low<< " to " << high<< " are\n" ;
segmentedSieve(low, high);
}
|
Java
import java.util.*;
import java.lang.Math;
public class Main{
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 )
{
chprime.add(i);
}
}
}
public static void segmentedSieve( int low, int high)
{
ArrayList<Integer> chprime= new ArrayList<Integer>();
fillPrime(chprime,high);
boolean [] prime= new boolean [high-low+ 1 ];
Arrays.fill(prime, true );
for ( int i:chprime)
{
int lower=(low/i);
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)
{
int low= 2 ;
int high= 100 ;
System.out.println( "Primes in Range " +low+ " to " +high+ " are " );
segmentedSieve(low,high);
}
}
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class main {
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 ) {
chprime.Add(i);
}
}
}
public static void segmentedSieve( int low, int high)
{
List< int > chprime = new List< int >();
fillPrime(chprime, high);
bool [] prime = new bool [high - low + 1];
Array.Fill(prime, true );
foreach ( int i in chprime)
{
int lower = (low / i);
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)
{
int low = 2;
int high = 100;
Console.WriteLine( "Primes in Range " + low + " to "
+ high + " are " );
segmentedSieve(low, high);
}
}
|
Python
import math
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)
def segmentedSieve(low, high):
chprime = list ()
fillPrimes(chprime, high)
prime = [ True ] * (high - low + 1 )
for i in chprime:
lower = (low / / i)
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 = " " )
low = 2
high = 100
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) {
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
}
if i == p {
i += p
}
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
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);
}
}
}
function segmentedSieve(low, high)
{
var chprime = [];
fillPrimes(chprime, high);
var prime = Array(high - low + 1).fill( true );
for (let i of chprime) {
var lower = Math.floor(low / i);
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 + " " );
}
}
}
var low = 2;
var high = 100;
process.stdout.write( "Primes in range " + low + " to "
+ high + " are\n" );
segmentedSieve(low, high);
|
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
Share your thoughts in the comments
Please Login to comment...