Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
class Solution {
public:
int countPrimes(int n) {
if(n < 2) return 0;
vector<int> visited(n, 0);
int cnt = 0;
for(int i=2; i<n; i++) {
if(visited[i]==1) continue;
cnt += 1;
for(int j=i+i; j < n; j+=i)
visited[j] = 1;
}
return cnt;
}
};
本文介绍了一种计算小于非负整数n的所有素数数量的方法。通过筛选法标记已知的合数,避免重复计算,提高了效率。感谢@mithmatt提供此问题及测试案例。
202

被折叠的 条评论
为什么被折叠?



