204. Count Primes
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
这道题参考了网上的方法,自己写了代码。AC了。需要注意是在比n小的数里面找,不含n。
class Solution {
public:
int countPrimes(int n) {
if(n<=2)return 0;
int ans=1;
set<int> t;
t.clear();
int p=1;
for(int i=2;i<n;i++)
{
if(t.count(i)==0)
{
p=2;
while(i*p<n)
{
t.insert(i*p);
p++;
}
}
}
return n-2-t.size();
}
};