The Wayback Machine - https://web.archive.org/web/20240810114425/https://www.geeksforgeeks.org/bitwise-sieve/
Open In App

Bitwise Sieve

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a number n, print all primes smaller than n.
Examples : 

Input : 30
Output : 2 3 5 7 11 13 17 19 23 29

Input : n = 100
Output : 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 

We know how to calculate all primes less than n by the Sieve of Eratosthenes. Below is an implementation of Sieve. 
One optimization in the below implementation is, we have skipped all even numbers altogether. 
We reduce the size of the prime array to half. We also reduce all iterations to half. 

C++




// C++ program to implement normal Sieve
// of Eratosthenes using simple optimization
// to reduce size of prime array to half and
// reducing iterations.
#include <bits/stdc++.h>
using namespace std;
  
void normalSieve(int n)
{
    // prime[i] is going to store true if
    // if i*2 + 1 is composite.
    bool prime[n/2];
    memset(prime, false, sizeof(prime));
  
    // 2 is the only even prime so we can
    // ignore that. Loop starts from 3.
    for (int i=3 ; i*i < n; i+=2)
    {
        // If i is prime, mark all its
        // multiples as composite
        if (prime[i/2] == false)
            for (int j=i*i; j<n; j+=i*2)
                prime[j/2] = true;
    }
  
    // writing 2 separately
    printf("2 ");
  
    // Printing other primes
    for (int i=3; i<n ; i+=2)
        if (prime[i/2] == false)
            printf( "%d " , i );
}
  
// Driver code
int main()
{
    int n = 100 ;
    normalSieve(n);
    return 0;
}


Java




// Java program to implement normal Sieve
// of Eratosthenes using simple optimization
// to reduce size of prime array to half and
// reducing iterations.
import java.util.Arrays;
  
class GFG
{
    static void normalSieve(int n)
    {
        // prime[i] is going to store true if
        // if i*2 + 1 is composite.
        boolean prime[]=new boolean[n / 2];
        Arrays.fill(prime, false);
      
        // 2 is the only even prime so we can
        // ignore that. Loop starts from 3.
        for (int i = 3 ; i * i < n; i += 2)
        {
            // If i is prime, mark all its
            // multiples as composite
            if (prime[i / 2] == false)
                for (int j = i * i; j < n; j += i * 2)
                    prime[j / 2] = true;
        }
      
        // writing 2 separately
        System.out.print("2 ");
      
        // Printing other primes
        for (int i = 3; i < n ; i += 2)
            if (prime[i / 2] == false)
                System.out.print(i + " ");
    }
    public static void main (String[] args)
    {
        int n = 100 ;
        normalSieve(n);
    }
}
  
// This code is contributed by Anant Agarwal.


Python3




# Sieve of Eratosthenes using 
# simple optimization to reduce 
# size of prime array to half and 
# reducing iterations.
def normalSieve(n):
  
    # prime[i] is going to store 
    # true if if i*2 + 1 is composite.
    prime = [0]*int(n / 2);
  
    # 2 is the only even prime so 
    # we can ignore that. Loop 
    # starts from 3.
    i = 3 ;
    while(i * i < n):
        # If i is prime, mark all its
        # multiples as composite
        if (prime[int(i / 2)] == 0):
            j = i * i;
            while(j < n): 
                prime[int(j / 2)] = 1;
                j += i * 2;
        i += 2;
  
    # writing 2 separately
    print(2,end=" ");
  
    # Printing other primes
    i = 3;
    while(i < n):
        if (prime[int(i / 2)] == 0):
            print(i,end=" ");
        i += 2;
  
  
# Driver code
if __name__=='__main__':
    n = 100 ;
    normalSieve(n);
  
# This code is contributed by mits.


C#




// C# program to implement normal Sieve
// of Eratosthenes using simple optimization
// to reduce size of prime array to half and
// reducing iterations.
using System;
  
namespace prime
{
    public class GFG
    {     
                  
        public static void normalSieve(int n)
        {
              
        // prime[i] is going to store true if
        // if i*2 + 1 is composite.
        bool[] prime = new bool[n/2];
          
        for(int i = 0; i < n/2; i++)
            prime[i] = false;
          
        // 2 is the only even prime so we can
        // ignore that. Loop starts from 3. 
        for(int i = 3; i*i < n; i = i+2)
        { 
            // If i is prime, mark all its
            // multiples as composite
            if (prime[i / 2] == false)
              
                for (int j = i * i; j < n; j += i * 2)
                    prime[j / 2] = true;
        }
          
        // writing 2 separately
        Console.Write("2 ");
      
        // Printing other primes
        for (int i = 3; i < n ; i += 2)
          
            if (prime[i / 2] == false)
                Console.Write(i + " ");
              
        }
          
        // Driver Code
        public static void Main()
        {
        int n = 100;
        normalSieve(n);
        }
    }
}
  
// This code is contributed by Sam007.


PHP




<?php
// PHP program to implement normal 
// Sieve of Eratosthenes using 
// simple optimization to reduce  
// size of prime array to half and 
// reducing iterations.
function normalSieve($n)
{
    // prime[i] is going to store 
    // true if if i*2 + 1 is composite.
    $prime = array_fill(0, (int)($n / 2), 
                                  false);
  
    // 2 is the only even prime so 
    // we can ignore that. Loop 
    // starts from 3.
    for ($i = 3 ; $i * $i < $n; $i += 2)
    {
        // If i is prime, mark all its
        // multiples as composite
        if ($prime[$i / 2] == false)
            for ($j = $i * $i; $j < $n; 
                          $j += $i * 2)
                $prime[$j / 2] = true;
    }
  
    // writing 2 separately
    echo "2 ";
  
    // Printing other primes
    for ($i = 3; $i < $n ; $i += 2)
        if ($prime[$i / 2] == false)
            echo $i . " ";
}
  
// Driver code
$n = 100 ;
normalSieve($n);
  
// This code is contributed by mits.
?>


Javascript




<script>
// javascript program to implement normal Sieve
// of Eratosthenes using simple optimization
// to reduce size of prime array to half and
// reducing iterations.
function normalSieve(n)
{
  
        // prime[i] is going to store true if
        // if i*2 + 1 is composite.
        var prime = Array(n / 2).fill(false);
          
  
        // 2 is the only even prime so we can
        // ignore that. Loop starts from 3.
        for (i = 3; i * i < n; i += 2)
        {
          
            // If i is prime, mark all its
            // multiples as composite
            if (prime[parseInt(i / 2)] == false)
                for (j = i * i; j < n; j += i * 2)
                    prime[parseInt(j / 2)] = true;
        }
  
        // writing 2 separately
        document.write("2 ");
  
        // Printing other primes
        for (i = 3; i < n; i += 2)
            if (prime[parseInt(i / 2)] == false)
                document.write(i + " ");
    }
      
        var n = 100;
        normalSieve(n);
  
// This code is contributed by todaysgaurav. 
</script>


Output : 
 

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(nlogn)

Space Complexity: O(n)
Further optimization using bitwise operators. 
The above implementation uses bool data type which takes 1 byte. We can optimize space to n/8 by using individual bits of an integer to represent individual primes. We create an integer array of size n/64. Note that the size of the array is reduced to n/64 from n/2 (Assuming that integers take 32 bits). 
 

C++




// C++ program to implement bitwise Sieve
// of Eratosthenes.
#include <bits/stdc++.h>
using namespace std;
  
// Checks whether x is prime or composite
bool ifnotPrime(int prime[], int x)
{
    // checking whether the value of element
    // is set or not. Using prime[x/64], we find
    // the slot in prime array. To find the bit
    // number, we divide x by 2 and take its mod
    // with 32.
    return (prime[x/64] & (1 << ((x >> 1) & 31)));
}
  
// Marks x composite in prime[]
bool makeComposite(int prime[], int x)
{
    // Set a bit corresponding to given element.
    // Using prime[x/64], we find the slot in prime 
    // array. To find the bit number, we divide x
    // by 2 and take its mod with 32.
    prime[x/64] |= (1 << ((x >> 1) & 31));
}
  
// Prints all prime numbers smaller than n.
void bitWiseSieve(int n)
{
    // Assuming that n takes 32 bits, we reduce
    // size to n/64 from n/2.
    int prime[n/64];
  
    // Initializing values to 0 .
    memset(prime, 0, sizeof(prime));
  
    // 2 is the only even prime so we can ignore that
    // loop starts from 3 as we have used in sieve of
    // Eratosthenes .
    for (int i = 3; i * i <= n; i += 2) {
  
        // If i is prime, mark all its multiples as
        // composite
        if (!ifnotPrime(prime, i))
            for (int j = i * i, k = i << 1; j < n; j += k)
                makeComposite(prime, j);
    }
  
    // writing 2 separately
    printf("2 ");
  
    // Printing other primes
    for (int i = 3; i <= n; i += 2)
        if (!ifnotPrime(prime, i))
            printf("%d ", i);
}
  
// Driver code
int main()
{
    int n = 30;
    bitWiseSieve(n);
    return 0;
}


Java




// JAVA Code to implement Bitwise 
// Sieve of Eratosthenes.
import java.util.*;
  
class GFG {
      
    // Checks whether x is prime or composite
    static int ifnotPrime(int prime[], int x)
    {
        // checking whether the value of element
        // is set or not. Using prime[x/64], 
        // we find the slot in prime array. 
        // To find the bit number, we divide x
        // by 2 and take its mod with 32.
        return (prime[x/64] & (1 << ((x >> 1) & 31)));
    }
       
    // Marks x composite in prime[]
    static void makeComposite(int prime[], int x)
    {
        // Set a bit corresponding to given element.
        // Using prime[x/64], we find the slot 
        // in prime array. To find the bit number,
        // we divide x by 2 and take its mod with 32.
        prime[x/64] |= (1 << ((x >> 1) & 31));
    }
       
    // Prints all prime numbers smaller than n.
    static void bitWiseSieve(int n)
    {
        // Assuming that n takes 32 bits, 
        // we reduce size to n/64 from n/2.
        int prime[] = new int[n/64 + 1];
       
       
        // 2 is the only even prime so we
        // can ignore that loop starts from
        // 3 as we have used in sieve of
        // Eratosthenes .
        for (int i = 3; i * i <= n; i += 2) {
       
            // If i is prime, mark all its 
            // multiples as composite
            if (ifnotPrime(prime, i)==0)
                for (int j = i * i, k = i << 1; 
                                  j < n; j += k)
                    makeComposite(prime, j);
        }
       
        // writing 2 separately
        System.out.printf("2 ");
       
        // Printing other primes
        for (int i = 3; i <= n; i += 2)
            if (ifnotPrime(prime, i) == 0)
                System.out.printf("%d ", i);
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int n = 30;
        bitWiseSieve(n);
    }
}
  
// This code is contributed by Arnav Kr. Mandal.    


Python3




# Python3 program to implement 
# bitwise Sieve of Eratosthenes.
  
# Checks whether x is 
# prime or composite 
def ifnotPrime(prime, x):
  
    # Checking whether the value 
    # of element is set or not. 
    # Using prime[x/64], we find 
    # the slot in prime array. 
    # To find the bit we divide 
    # x by 2 and take its mod 
    # with 32.
    return (prime[int(x / 64)] & 
           (1 << ((x >> 1) & 31)))
  
# Marks x composite in prime[]
def makeComposite(prime, x):
    
    # Set a bit corresponding to 
    # given element. Using prime[x/64],
    # we find the slot in prime array.  
    # To find the bit number, we divide x 
    # by 2 and take its mod with 32.
    prime[int(x / 64)] |= 
    (1 << ((x >> 1) & 31))
  
# Prints all prime numbers 
# smaller than n.
def bitWiseSieve(n):
  
    # Assuming that n takes 32 bits, 
    # we reduce size to n/64 from n/2.
    # Initializing values to 0.
    prime = [0 for i in range(int(n / 64) + 1)]
  
    # 2 is the only even prime so 
    # we can ignore that loop 
    # starts from 3 as we have used  
    # in sieve of Eratosthenes
    for i in range(3, n + 1, 2):
        if(i * i <= n):
  
            # If i is prime, mark all 
            # its multiples as composite 
            if(ifnotPrime(prime, i)):
                continue
            else:
                k = i << 1                
                for j in range(i * i, n, k):
                    k = i << 1
                    makeComposite(prime, j)
                      
    # Writing 2 separately 
    print("2 ", end = "")
  
    # Printing other primes
    for i in range(3, n + 1, 2):
        if(ifnotPrime(prime, i)):
            continue
        else:
            print(i, end = " ")
              
# Driver code 
n = 30
bitWiseSieve(n)
  
# This code is contributed by avanitrachhadiya2155


C#




// C# Code to implement Bitwise 
// Sieve of Eratosthenes.
using System;
  
class GFG
{
  
// Checks whether x is 
// prime or composite
static int ifnotPrime(int[] prime, int x)
{
    // checking whether the value 
    // of element is set or not. 
    // Using prime[x/64], we find 
    // the slot in prime array. 
    // To find the bit number, we 
    // divide x by 2 and take its
    // mod with 32.
    return (prime[x / 64] & 
           (1 << ((x >> 1) & 31)));
}
  
// Marks x composite in prime[]
static void makeComposite(int[] prime, 
                          int x)
{
    // Set a bit corresponding to 
    // given element. Using prime[x/64],
    // we find the slot in prime array. 
    // To find the bit number, we divide 
    // x by 2 and take its mod with 32.
    prime[x / 64] |= (1 << ((x >> 1) & 31));
}
  
// Prints all prime numbers
// smaller than n.
static void bitWiseSieve(int n)
{
    // Assuming that n takes 32 bits, 
    // we reduce size to n/64 from n/2.
    int[] prime = new int[(int)(n / 64) + 1];
  
  
    // 2 is the only even prime so we
    // can ignore that loop starts from
    // 3 as we have used in sieve of
    // Eratosthenes .
    for (int i = 3; i * i <= n; i += 2)
    {
  
        // If i is prime, mark all its 
        // multiples as composite
        if (ifnotPrime(prime, i) == 0)
            for (int j = i * i, k = i << 1; 
                             j < n; j += k)
                makeComposite(prime, j);
    }
  
    // writing 2 separately
    Console.Write("2 ");
  
    // Printing other primes
    for (int i = 3; i <= n; i += 2)
        if (ifnotPrime(prime, i) == 0)
            Console.Write(i + " ");
}
  
// Driver Code
static void Main() 
{
    int n = 30;
    bitWiseSieve(n);
}
}
  
// This code is contributed by mits 


PHP




<?php
// PHP program to implement 
// bitwise Sieve of Eratosthenes.
$prime;
  
// Checks whether x is
// prime or composite
function ifnotPrime($x)
{
    global $prime;
      
    // checking whether the value 
    // of element is set or not. 
    // Using prime[x/64], we find
    // the slot in prime array. 
    // To find the bit number, we 
    // divide x by 2 and take its 
    // mod with 32.
    return $a = ($prime[(int)($x / 64)] & 
                        (1 << (($x >> 1) & 31)));
}
  
// Marks x composite in prime[]
function makeComposite($x)
{
    global $prime;
      
    // Set a bit corresponding to
    // given element. Using prime[x/64], 
    // we find the slot in prime 
    // array. To find the bit number,
    // we divide x by 2 and take its
    // mod with 32.
    $prime[(int)($x / 64)] |= 
                (1 << (($x >> 1) & 31));
}
  
// Prints all prime 
// numbers smaller than n.
function bitWiseSieve($n)
{
    global $prime;
      
    // Assuming that n takes 
    // 32 bits, we reduce
    // size to n/64 from n/2.
    // Initializing values to 0 .
    $prime = array_fill(0, 
                   (int)ceil($n / 64), 0);
                     
    // 2 is the only even prime 
    // so we can ignore that
    // loop starts from 3 as we 
    // have used in sieve of
    // Eratosthenes .
    for ($i = 3; $i * $i <= $n; $i += 2) 
    {
  
        // If i is prime, mark 
        // all its multiples as
        // composite
        if (!ifnotPrime($i))
            for ($j = $i * $i, 
                 $k = $i << 1; 
                 $j < $n; $j += $k)
                makeComposite($j);
    }
  
    // writing 2 separately
    echo "2 ";
  
    // Printing other primes
    for ($i = 3; $i <= $n; $i += 2)
        if (!ifnotPrime($i))
            echo $i." ";
}
  
// Driver code
$n = 30;
bitWiseSieve($n);
  
// This code is contributed
// by mits. 
?>


Javascript




<script>
  
// javascript Code to implement Bitwise 
// Sieve of Eratosthenes.
     
// Checks whether x is prime or composite
function ifnotPrime(prime , x)
{
    // checking whether the value of element
    // is set or not. Using prime[x/64], 
    // we find the slot in prime array. 
    // To find the bit number, we divide x
    // by 2 and take its mod with 32.
    return (prime[x/64] & (1 << ((x >> 1) & 31)));
}
   
// Marks x composite in prime
function makeComposite(prime , x)
{
    // Set a bit corresponding to given element.
    // Using prime[x/64], we find the slot 
    // in prime array. To find the bit number,
    // we divide x by 2 and take its mod with 32.
    prime[x/64] |= (1 << ((x >> 1) & 31));
}
   
// Prints all prime numbers smaller than n.
function bitWiseSieve(n)
{
    // Assuming that n takes 32 bits, 
    // we reduce size to n/64 from n/2.
    var prime = Array.from({length: (n/64 + 1)}, (_, i) => 0);
   
   
    // 2 is the only even prime so we
    // can ignore that loop starts from
    // 3 as we have used in sieve of
    // Eratosthenes .
    for (var i = 3; i * i <= n; i += 2) {
   
        // If i is prime, mark all its 
        // multiples as composite
        if (ifnotPrime(prime, i)==0)
            for (var j = i * i, k = i << 1; 
                              j < n; j += k)
                makeComposite(prime, j);
    }
   
    // writing 2 separately
    document.write("2 ");
   
    // Printing other primes
    for (var i = 3; i <= n; i += 2)
        if (ifnotPrime(prime, i) == 0)
            document.write(i+" ");
}
  
/* Driver program to test above function */
var n = 30;
bitWiseSieve(n);   
  
// This code is contributed by 29AjayKumar 
</script>


Output: 
 

2 3 5 7 11 13 17 19 23 29

Time Complexity: O(nlogn)

Space Complexity: O(n)



Previous Article
Next Article

Similar Reads

Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
Given an array arr[] of size N. The task is to find the number of pairs (arr[i], arr[j]) as cntAND, cntOR, and cntXOR such that: cntAND: Count of pairs where bitwise AND of least significant bits is 1.cntOR: Count of pairs where bitwise OR of least significant bits is 1.cntXOR: Count of pairs where bitwise XOR of least significant bits is 1. Exampl
7 min read
Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND
Given an array arr[] consisting of N positive integers, replace pairs of array elements whose Bitwise AND exceeds Bitwise XOR values by their Bitwise AND value. Finally, count the maximum number of such pairs that can be generated from the array. Examples: Input: arr[] = {12, 9, 15, 7}Output: 2Explanation:Step 1: Select the pair {12, 15} and replac
9 min read
Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values
Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers. Examples: Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A &amp; B = 2, then the possible value of A and B is 3 and 6 respe
7 min read
Number of unmarked integers in a special sieve
Given an array A containing numbers from 2 to N.. A special type of sieving is done on it . The procedure of sieving is as follows: Create an array with elements as consecutive integers from 2 to N and mark every element in the array as unmarked.Let an integer Q = N and mark all the proper divisors of Q except Q itself in the array.Find the largest
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 and mark it as composite. This process continues unt
3 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 Explanation: Maximum contiguous prime number sequence i
13 min read
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 = 20Output : Sum = 60Prime numbers between [10, 20] are:11, 13, 17, 19Therefore, sum = 11 + 13 + 17 + 19 = 60Input : L = 15, R = 25Output : Sum = 59Recommended: Please try your approach on {IDE} first
12 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 Sieve of Eratosthenes, then print all prime numbers i
15 min read
Sieve of Atkin
Given a limit, print all prime numbers smaller than or equal to the given limit. Examples: Input: limit = 10Output: 2, 3, 5, 7 Input: limit = 20Output: 2, 3, 5, 7, 11, 13, 17, 19 Other Approaches: The prime numbers till a limit can be generated using other algorithms, such as: Sieve of Eratosthenes: O(N*log(log(N)))Sieve of Sundaram: O(N*log N) Sie
15+ 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 : int N = 20 Output : 2 3 5 7 11 13 17 19 Manipulat
12 min read
three90RightbarBannerImg