class Solution {
public:
int countPrimes(int n) {
vector<bool> isPrim(n, true);
for(int i = 2; i * i < n; i++) { //不能 i * i <= n
if(isPrim[i]) {
// i 的倍数不可能是素数了
/*
这样可以把 i 的整数倍都标记为 false,但是仍然存在计算冗余。
比如 n = 25,i = 4 时算法会标记 4 × 2 = 8,4 × 3 = 12 等等数字,但是这两个数字已经被 i = 2 和 i = 3 的 2 × 4 和 3 × 4 标记了。我们可以稍微优化一下,让 j 从 i 的平方开始遍历,而不是从 2 * i 开始
*/
for(int j = 2 * i; j < n; j += i) { //不能j <= n
isPrim[j] = false;
}
}
}
int count = 0;
for(int i = 2; i < n; i++) {
if(isPrim[i]) count++;
}
return count;
}
};
class Solution {
public:
int countPrimes(int n) {
vector<bool> isPrim(n, true);
for(int i = 2; i * i < n; i++) {
if(isPrim[i]) {
for(int j = i * i; j < n; j += i) { //优化
isPrim[j] = false;
}
}
}
int count = 0;
for(int i = 2; i < n; i++) {
if(isPrim[i]) count++;
}
return count;
}
};
LeetCode204. 计数质数
最新推荐文章于 2023-03-09 07:00:00 发布