Bitwise Sieve in C++


In this problem, we are given a number N. Our task is to find all prime numbers smaller than N using Bitwise Sieve.

Bitwise sieve is an optimized version of Sieve of Eratosthenes which is used to find all prime numbers smaller than the given number.

Let’s take an example to understand the problem,

Input − N = 25

Output − 2 3 5 7 11 13 17 19 23

The bitwise sieve works in the same ways as the normal sieve. It just we will use the bits of integers of represent primes instead of a boolean type. This will reduce the space complexity to 1/8 times.

Example

Let’s see the code to understand the solution,

 Live Demo

#include <iostream>
#include <math.h>
#include <cstring>
using namespace std;
bool ifnotPrime(int prime[], int x) {
   return (prime[x/64]&(1<<((x>>1)&31)));
}
bool makeComposite(int prime[], int x) {
   prime[x/64]|=(1<<((x>>1)&31));
}
void bitWiseSieve(int n){
   int prime[n/64];
   memset(prime, 0, sizeof(prime));
   for (int i = 3; i<= sqrt(n); i= i+2) {
      if (!ifnotPrime(prime, i))
      for (int j=pow(i,2), k= i<<1; j<n; j+=k)
      makeComposite(prime, j);
   }
   for (int i = 3; i <= n; i += 2)
   if (!ifnotPrime(prime, i))
      printf("%d\t", i);
}
int main(){
   int N = 37;
   printf("All the prime number less than %d are 2\t", N);
   bitWiseSieve(N);
   return 0;
}

Output

All the prime number less than 37 are 2 3 5 7 11 13 17 19 23 29 31 37

Updated on: 05-Aug-2020

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements