Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added 204_count_primes_leetcode_seive_of_erathosthenes.cpp #1033

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions C++/204_count_primes_leetcode_seive_of_erathosthenes.cpp
Original file line number Diff line number Diff line change
@@ -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 <bool> 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;
}
};