Skip to content

Commit 0038bad

Browse files
Implemented seive of erathsthenes in cpp
1 parent 52e7c9c commit 0038bad

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
title: Sieve of Eratosthenes
3+
description: Generate all prime numbers up to a given integer using the Sieve of Eratosthenes algorithm
4+
tags: number, prime
5+
author: dibyam-jalan27
6+
---
7+
8+
```cpp
9+
#include <vector>
10+
11+
using namespace std;
12+
13+
vector<int> sieve_of_eratosthenes(int n) {
14+
vector<bool> is_prime(n + 1, true);
15+
vector<int> primes;
16+
is_prime[0] = is_prime[1] = false;
17+
for (int i = 2; i * i <= n; ++i) {
18+
if (is_prime[i]) {
19+
for (int j = i * i; j <= n; j += i) {
20+
is_prime[j] = false;
21+
}
22+
}
23+
}
24+
for (int i = 2; i <= n; ++i) {
25+
if (is_prime[i]) {
26+
primes.push_back(i);
27+
}
28+
}
29+
return primes;
30+
}
31+
32+
// Usage:
33+
sieve_of_eratosthenes(30); // Returns: {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}
34+
```

0 commit comments

Comments
 (0)