Bitwise Sieve

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 Sieve of Eratosthenes. Below is an implementation of Sieve.
One optimization in below implementation is, we have skipped all even numbers altogether.
We reduce size of 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 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

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 = *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



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

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

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

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

Output:

2 3 5 7 11 13 17 19 23 29

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : Mithun Kumar