class Solution {
public:
int countPrimes(int n) {
if(n<3) return 0;
vector<bool> nums(n,true);
for(int i=2; i*i<n; i++){ // i*i<n减少循环次数
if(nums[i]){
for(int j=i*i ;j<n; j=j+i){ //从i*i开始,避免之前已经遇到过的数
nums[j]=false;
}
}
}
int cnt=0;
for(int i=2; i<n; i++){
if(nums[i]) cnt++;
}
return cnt;
}
};
09-11
143
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-01
07-01
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交