From 30afdb2b3bfeedc8dfc96cd10fc85ba3d624541a Mon Sep 17 00:00:00 2001 From: Ansh Date: Wed, 6 Oct 2021 00:16:03 +0530 Subject: [PATCH] Create 204_count_primes_leetcode_seive_of_erathosthenes.cpp Solution of 204. | Count Primes | C++ | Leetcode --- ...primes_leetcode_seive_of_erathosthenes.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/204_count_primes_leetcode_seive_of_erathosthenes.cpp diff --git a/C++/204_count_primes_leetcode_seive_of_erathosthenes.cpp b/C++/204_count_primes_leetcode_seive_of_erathosthenes.cpp new file mode 100644 index 0000000..36a3550 --- /dev/null +++ b/C++/204_count_primes_leetcode_seive_of_erathosthenes.cpp @@ -0,0 +1,30 @@ +// Problem Link : https://leetcode.com/problems/count-primes/ + +class Solution { +public: + int countPrimes(int n) { + long long int i, j, ans = 0; + vector isprime(n + 1, true); // true if prime otherwise false + isprime[0] = isprime[1] = false; // 0, 1 are not prime numbers + +// Using seive of erathosthenes to find the prime number numbers in the range from 1 to n + for (i = 2; i * i <= n; i++) + { + if (isprime[i]) + { + for (j = i * i; j <= n; j = j + i) // once i * i >= n, then j = j + i always > n, so use of checking those index / numbers + { + isprime[j] = false; + } + } + } + + for (i = 1; i < n; i++) // Checking which all are primes numbers till n (n excluded) + { + if (isprime[i]) + ans++; + } + + return ans; + } +};