
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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,
#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
- Related Articles
- Sieve of Eratosthenes in java
- Python Program for Sieve of Eratosthenes
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python
- Bitwise Operators in C
- Bitwise Operators in C++
- Bitwise NOT in Arduino
- Bitwise XOR in Arduino
- Bitwise operators in Dart Programming
- Python Bitwise Operators
- Java Bitwise Operators
- Perl Bitwise Operators
- Using Sieve of Eratosthenes to find primes JavaScript
- Bitwise ORs of Subarrays in C++
- What is Bitwise XOR in C++?
- What is Bitwise AND in C++?

Advertisements