Bitwise Sieve - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Count set bits in an integer
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
How to swap two numbers without using a temporary variable?
Compute the integer absolute value (abs) without branching
Program to find whether a given number is power of 2
Binary representation of a given number
Little and Big Endian Mystery
Josephus problem | Set 1 (A O(n) Solution)
Cyclic Redundancy Check and Modulo-2 Division
Add two numbers without using arithmetic operators
Find the element that appears once
Bits manipulation (Important tactics)
Rotate bits of a number
C++ bitset and its application
Find the Number Occurring Odd Number of Times
Divide two integers without using multiplication, division and mod operator
Count total set bits in all numbers from 1 to n
1's and 2's complement of a Binary Number
Bit Fields in C
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Find most significant set bit of a number
Bitwise Right Shift Operators in Java
Operators in C | Set 2 (Relational and Logical Operators)
Position of rightmost set bit
Rotate bits of a number
Write an Efficient C Program to Reverse Bits of a Number
Determine if a string has all Unique Characters
Check whether K-th bit is set or not
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Count set bits in an integer
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
How to swap two numbers without using a temporary variable?
Compute the integer absolute value (abs) without branching
Program to find whether a given number is power of 2
Binary representation of a given number
Little and Big Endian Mystery
Josephus problem | Set 1 (A O(n) Solution)
Cyclic Redundancy Check and Modulo-2 Division
Add two numbers without using arithmetic operators
Find the element that appears once
Bits manipulation (Important tactics)
Rotate bits of a number
C++ bitset and its application
Find the Number Occurring Odd Number of Times
Divide two integers without using multiplication, division and mod operator
Count total set bits in all numbers from 1 to n
1's and 2's complement of a Binary Number
Bit Fields in C
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Find most significant set bit of a number
Bitwise Right Shift Operators in Java
Operators in C | Set 2 (Relational and Logical Operators)
Position of rightmost set bit
Rotate bits of a number
Write an Efficient C Program to Reverse Bits of a Number
Determine if a string has all Unique Characters
Check whether K-th bit is set or not
Difficulty Level :
Medium
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++
Java
Python3
C#
PHP
Javascript
// 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 codeint main(){    int n = 100 ;    normalSieve(n);    return 0;}
// 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.
# 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 codeif __name__=='__main__':    n = 100 ;    normalSieve(n); # This code is contributed by mits.
// 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 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.?>
<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 
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++
Java
Python3
C#
PHP
Javascript
// C++ program to implement bitwise Sieve// of Eratosthenes.#include <bits/stdc++.h>using namespace std; // Checks whether x is prime or compositebool 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 codeint main(){    int n = 30;    bitWiseSieve(n);    return 0;}
// 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 program to implement# bitwise Sieve of Eratosthenes. # Checks whether x is# prime or compositedef 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 coden = 30bitWiseSieve(n) # This code is contributed by avanitrachhadiya2155
// C# Code to implement Bitwise// Sieve of Eratosthenes.using System; class GFG{ // Checks whether x is// prime or compositestatic 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 Codestatic void Main(){    int n = 30;    bitWiseSieve(n);}} // This code is contributed by mits
<?php// PHP program to implement// bitwise Sieve of Eratosthenes.$prime; // Checks whether x is// prime or compositefunction 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.?>
<script> // javascript Code to implement Bitwise// Sieve of Eratosthenes.    // Checks whether x is prime or compositefunction 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 primefunction 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
Mithun Kumar
avanitrachhadiya2155
todaysgaurav
29AjayKumar
Prime Number
sieve
Bit Magic
Technical Scripter
Bit Magic
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether bitwise AND of a number with any subset of an array is zero or not
Find the size of Largest Subset with positive Bitwise AND
Write an Efficient Method to Check if a Number is Multiple of 3
Highest power of 2 less than or equal to given number
Check for Integer Overflow
Swap two nibbles in a byte
Swap bits in a given number
Reverse actual bits of the given number
Bit Tricks for Competitive Programming