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 1 commit
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
Next Next commit
Add Sieve of Eratosthenes algorithm snippet in C++
  • Loading branch information
muriloguizelin committed Jan 3, 2025
commit 4b58d540fc35042a72ca2abeb2a11188950d5810
29 changes: 29 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,29 @@
---
title: Sieve of Eratosthenes
description: Generates all prime numbers up to a given maximum value using an efficient algorithm.
author: muriloguizelin
tags: number-theory, prime, sieve
---
```cpp

#include <vector>

const int MAXN = 1e6 + 1;
std::vector<bool> isPrime(MAXN, true);

void sieve() {
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;
}
}
}
}

// Usage:.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Remove the dot . after the colon :

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

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