204. Count Primes
problem description
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.algorithm thought
code
class Solution {
public:
int countPrimes(int n) {
if(n<=2)
return 0;
vector<bool> dp(n,false);
int half=sqrt(n);
int res=1;
for(int i=3;i<n;i+=2){
if(dp[i])
continue;
res++;
if(i>half)
continue;
for(int j=i*i;j<n;j+=2*i){
dp[j]=true;
}
}
return res;
}
};algorithm analysis
Last updated