问题描述:
Count the number of prime numbers less than a non-negative number, n.
问题分析:
题目要求出小于n的素数的个数,当n<=2时,个数为0;
大于2时,我们只需要将其他的非素数求出,然后用总数减去它即为素数的个数。
过程详见代码:
class Solution {
public:
int countPrimes(int n) {
if(n <= 2) return 0;
vector<int> v(n + 1, 0);
int res = 0;
for(int i = 2; i * i < n; i++)
{
for(int j = i * i; j < n; j += i)
{
if(!v[j])
{
v[j] = 1;
res++;
}
}
}
return n - 2 - res;
}
};
本文介绍了一种计算小于非负整数n的素数数量的方法。当n小于等于2时,素数数量为0;当n大于2时,通过标记非素数并计算剩余数目的方式得出结果。

5968

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



