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

Create leetcode204.cpp #1329

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
32 changes: 32 additions & 0 deletions C++/leetcode204.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
204. Count Primes
Given an integer n, return the number of prime numbers that are strictly less than n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
*/
class Solution {
public:
int countPrimes(int n) {
if(n == 0)
return 0;
vector<bool> prime(n,true);
prime[0] = prime [1] = false ;
int ans = 0;
for(int i = 2 ; i<n ; i++)
{
if(prime[i])
{
ans++;
int j=2*i;
while(j<n)
{
prime[j] = false;
j = j + i ;
}
}
}
return ans;
}
};