From 6398781b4bedd9ed982ac4804228819eefc307cd Mon Sep 17 00:00:00 2001 From: Vatsalya Gupta <64428075+vatsalya-gupta@users.noreply.github.com> Date: Fri, 2 Oct 2020 15:26:15 +0530 Subject: [PATCH] Create sieveOfEratosthenes.cpp --- sieveOfEratosthenes.cpp | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 sieveOfEratosthenes.cpp diff --git a/sieveOfEratosthenes.cpp b/sieveOfEratosthenes.cpp new file mode 100644 index 0000000..6a7a8b7 --- /dev/null +++ b/sieveOfEratosthenes.cpp @@ -0,0 +1,44 @@ +/* + Sieve of Eratosthenes: + Given a number n, print all prime numbers less than n +*/ + +#include +using namespace std; + +void sieve_of_eratosthenes(int n) +{ + /* + This will print all + prime number less than n + */ + + // Initially all are prime + bool *prime = new bool[n]; + for (int i = 0; i < n; i++) + { + prime[i] = true; + } + + // Now we start marking multiples of every number non-prime + for (int i = 2; i * i <= n; i++) + { + // We start from first multiple and go till n + for (int j = 2 * i; j < n; j += i) + { + prime[j] = false; + } + } + for (int i = 2; i < n; i++) + { + if (prime[i]) + { + cout << i << " "; + } + } +} + +int main() +{ + sieve_of_eratosthenes(50); +}