From 15c0ae012c1e3958e4a911ee648f2d127eb3c325 Mon Sep 17 00:00:00 2001 From: Masoom9587 <93204893+Masoom9587@users.noreply.github.com> Date: Fri, 21 Oct 2022 12:06:50 +0530 Subject: [PATCH] Sieve of Eratosthenes The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so #cpp #c++ --- seive.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 seive.cpp diff --git a/seive.cpp b/seive.cpp new file mode 100644 index 00000000..3fd4caf6 --- /dev/null +++ b/seive.cpp @@ -0,0 +1,32 @@ +// the following implementation +// stores only halves of odd numbers +// the algorithm is a faster by some constant factors + +#include +#include +using namespace std; + +bitset<500001> Primes; +void SieveOfEratosthenes(int n) +{ + Primes[0] = 1; + for (int i = 3; i*i <= n; i += 2) { + if (Primes[i / 2] == 0) { + for (int j = 3 * i; j <= n; j += 2 * i) + Primes[j / 2] = 1; + } + } +} + +int main() +{ + int n = 100; + SieveOfEratosthenes(n); + for (int i = 1; i <= n; i++) { + if (i == 2) + cout << i << ' '; + else if (i % 2 == 1 && Primes[i / 2] == 0) + cout << i << ' '; + } + return 0; +}