Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add Sieve of Eratosthenes algorithm snippet in C++ #160

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
muriloguizelin wants to merge 3 commits into quicksnip-dev:main from muriloguizelin:main
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
View file Open in desktop
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;
```

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /