题目链接:https://leetcode.com/problems/count-primes/
Description:
Count the number of prime numbers less than a non-negative number, n.
思路:筛选法求素数
代码如下:
class Solution {
public:
int countPrimes(int n) {
if(n < 1) return 0;
vector<bool> hash(n, true);
hash[1] = false;
for(int i = 2; i < n; i++)
{
if(!hash[i]) continue;
for(int j = 2*i; j < n; j+=i)
hash[j] = false;
}
int ans = 0;
for(int i =2; i<n; i++) ans = hash[i]?ans+1:ans;
return ans;
}
};