Skip to content
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions snippets/cpp/math-and-numbers/sieve-of-eratosthenes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
title: Sieve of Eratosthenes
description: Generates all prime numbers up to a given maximum value using an efficient algorithm using bitset.
author: muriloguizelin
tags: number-theory, prime, sieve
---

```cpp
#include <bitset>
#include <iostream>

constexpr int MAXN = 1e6 + 1;

consteval auto computeSieve() {
std::bitset<MAXN> isPrime;
isPrime.set();
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i < MAXN; ++i) {
if (isPrime[i]) {
for (int j = i * i; j < MAXN; j += i) {
isPrime[j] = false;
}
}
}
return isPrime;
}

// Usage:
computeSieve();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to update this line too

if (isPrime[29]) std::cout << "29 is a prime number!" << std::endl;
```