DEV Community

Cover image for Sieve of Eratosthenes: What is it? And how to implement sieve in C++
Alice Lee
Alice Lee

Posted on

Sieve of Eratosthenes: What is it? And how to implement sieve in C++

What is Sieve of Eratosthenes

Sive of Eratosthenes is one an ancient algorithm that finds all prime numbers in a given range. It is also used for finding all divisors of a number with a faster time complexity.

Sieve Algorithm

  1. The algorithm starts by generating a boolean array Boolarray to store whether i is a prime number or not. 2. Every number in the array is set to be TRUE by default. 3. The outer loop of the algorithm iterates Boolarray from 2 to sqrt(n) . - Inner loop iterates through j and accumulate by i(for all multiples of i), all multiples are marked FALSE(since these are not prime numbers). - Inner loop works by marking FALSE on all multiples of i
  1. We are left with b with all prime numbers being TRUE in the range of 1 to n.

Time Complexity

The time complexity of the above logic is O(n log log n). The outer loop runs for sqrt(n), while the inner loop runs roughly n / i times.

Example in C++

#include<iostream>
using namespace std;

int main(){
    int n;
    cin>>n;
    bool Boolarray[n+1];
    for(int i = 2; i <= n; i++) {
    Boolarray[i]=true;
    }
    for (int i = 2; i * i <= n; i++) {
    if (Boolarray[j] == true) {
        for (int j = 2 * i; j <= n; j += i) {
        Boolarray[k] = false;
        }
    }
    }
    for(int i = 2; i <= n; i++) {
        if(Boolarray[i]==true)
            cout<<i<<" ";
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Image Source https://cp-algorithms.com/algebra/sieve-of-eratosthenes.html

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay