ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Sieve Of Eratosthenes

prodevelopertutorial August 18, 2019

Introduction:

Sieve Of Eratosthenes is one of the mose simple and efficient algorithm to find the prime numbers for a given set of limit.

Working of the algorithm:

The working of algorithm is very simple.

Step 1: First we write down all the numbers from 2 to n.
Step 2: From the first prime number i.e “2”, we strike out / remove all the numbers that are divisible by 2 till “n”.
Step 3: Then go to the next prime number, now strike out the numbers that are divisible by the present prime number till the square of the present prime number.
Step 4: Repeat step 3, till you reach the end.
Step 5: You will get the list of all the prime numbers.

Understanding Sieve Of Eratosthenes using an example:

In this example, we need all the prime numbers from 2 to 30. Below with the help of the image, I have explained the above steps.

Step 1: Write down all the numbers from 2 to n.

Sieve Of Eratosthenes

Step 2: From the number “2”, strike out all the multiple of 2. Here we have represented strike out in red color.

Sieve Of Eratosthenes

Step 3: Then go to the next prime number, now strike out the numbers that are divisible by the present prime number till the square of the present prime number. Here the next prime is 3, it’s square is 9. Hence strike out all the numbers that are multiple of 3 till 9. As 6 is already striked out earlier, we strike out 9 now.

Sieve Of Eratosthenes

Repeat step 3, till we reach the end. We shall try one more pass.

Now the next prime is “5”, it’s square is 25. Strike out all the numbers that are multiple of 5 till 25. i.e strikeout “10”, “15”, “20”, “25”. As “10” and “20” are already striked out, strike out “15” and “25”

Sieve Of Eratosthenes

Finally we shall left with the below numbers.

Sieve Of Eratosthenes

Implementation in C++

To implement in C++, we take a boolean array of size n and mark all the fields as true. Then we apply above steps, instead of striking out, we make the pirticular cell as false. Finally, we write down all the cell index is true.

#include <iostream>

using namespace std;

void sieve_of_eratosthenes(int n)
{
    //take a boolean array to store which index is a prime number.
    bool prime[n + 1];

    // make all the cells as true.
    for (int i = 2; i <= n; i++) 
    { 
        prime[i] = true; 
    } 

    // from the first prime number
    for(int j = 2; j*j <= n; j++)
    {
        // check if the current index is a prime number, if yes, then 
        if(prime[j] == true)
        {
            //if yes, then make all the cless that are multiple of that index as false
            for(int i = j*2; i <= n; i += j)
            {
                prime[i] = false;
            }
        }
    }

    cout<<" All the prime numbers from 2 to 30 is "<<endl;
    // from the first prime number, print all the prime numbers.
    for(int j = 2; j <= n; j++)
       if(prime[j]) // if prime[j] is true, then it is a prime number. Print it
          cout << j << " ";
}

int main()
{
    // n is the max limit to find the list of prime numbers from
    int n = 30;
    sieve_of_eratosthenes(n);
    return 0;
}

 

Output

2 3 5 7 11 13 17 19 23 29

 

Further Reading:

AJ’s definitive guide for DS and Algorithms. Click here to study the complete list of algorithm and data structure tutorial. 85+ chapters to study from.

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

2 Comments

  1. Atul Sharma
    Log in to Reply

    Hi, I got to know about your website today from your telegram channel and i enjoyed it while exploring, learned many new approach and specially the ad free experience.

    March 16, 2020
  2. Vishal Chauhan
    Log in to Reply

    Very simple explanation. Loving your work 🙂

    March 26, 2020

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT