From 0fd4ca4b1d08ecc7c6e095b9fbd7912a1e25db6e Mon Sep 17 00:00:00 2001 From: Akash Negi <55234838+NegiAkash890@users.noreply.github.com> Date: Tue, 18 May 2021 20:37:23 +0530 Subject: [PATCH] chore(CPlusPlus): add prime-sieve algorithm (#303) --- algorithms/CPlusPlus/Maths/prime-sieve.cpp | 31 ++++++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 algorithms/CPlusPlus/Maths/prime-sieve.cpp diff --git a/algorithms/CPlusPlus/Maths/prime-sieve.cpp b/algorithms/CPlusPlus/Maths/prime-sieve.cpp new file mode 100644 index 00000000..fb9f2779 --- /dev/null +++ b/algorithms/CPlusPlus/Maths/prime-sieve.cpp @@ -0,0 +1,31 @@ +//Sieve of Eratosthenes +//Print all prime numbers within given range. + +#include +using namespace std; +void PrimeSieve(int n) { + vector sieve(n + 1); //Create a vector array of size n+1 + fill(sieve.begin(), sieve.end(), 1); //Fill the array with 1s, which means all numbers are initially assumed to be prime. + sieve[0] = 0; //Exception:Zero is not a Prime + sieve[1] = 0; //Exception:One is not a Prime + for (int i = 2; i * i <= n; i++) { + if (sieve[i] == 1) { //This condition will only be executed if the sieve[i] is prime, mark all the multiples of Prime Numbers as non-prime. + for (int j = i * i; j <= n; j += i) { + sieve[j] = 0; + } + } + } + for (int i = 0; i < n; i++) { + if (sieve[i] == 1) { + cout << i << " "; + } + } + return; +} +int main() { + int n; + cin >> n; + PrimeSieve(n); //Call the function + return 0; //Time complexity : O(n*log(log(n))), Auxiliary Space: O(1) + //Example : n=10 , Output: 2 3 5 7 +} diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 695e4ef2..8be84cb0 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -66,3 +66,4 @@ # Maths 1. [Kaprekar Number](Maths/Kaprekar-number.cpp) 2. [Prime Number](Maths/prime-check.cpp) +3. [Prime Sieve](Maths/prime-sieve.cpp)