204. 计数质数
统计所有小于非负整数 n 的质数的数量。
思路
- 暴力法,判断每个数能否被整除
代码
class Solution {
public:
bool isPrimes(int n) {
for(int i = 2; i * i <= n; ++i) {
if(n % i == 0) {
return false;
}
}
return true;
}
int countPrimes(int n) {
int ans = 0;
for(int i = 2; i < n; ++i) {
if(isPrimes(i)) {
++ans;
}
}
return ans;
}
};
- 埃式筛,通过将已判断为质数的数字x,将其x * x, x *(x + 1)等都设定为合数。
代码
class Solution {
public:
int countPrimes(int n) {
vector<int> isPrime(n, 1);
int ans = 0;
for(int i = 2; i < n; i++) {
if(isPrime[i]) {
ans++;
if((long long)i * i < n) {
for(int j = i * i; j < n; j += i) {
isPrime[j] = 0;
}
}
}
}
return ans;
}
};