1,题目要求
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
计算小于非负数n的素数的数量。
2,题目思路
对于这道题,找出所有小于n的素数。
一般来说,素数的判断是一个非常常规的题目,而且一般来说判断整除时判断到sqrt(n)时即可。
还有一种方法,则是埃拉托色尼筛法求素数,即我们先假设所有的数字都是素数,然后当找到一个素数时,把素数的所有倍数筛出去,即可实现所有素数的寻找。
不过看了速度很快的算法,很多都是设置固定的大数素数结果判断结果,所以很快,个人觉着这种方法不可取。
3,代码实现
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
int countPrimes(int n) {
int i, k, res = 0;
vector<int> notPrime (n+2, false);
for(i = 2;i<n;i++){
if(notPrime[i])
continue;
res++;
for(k = 1;k*i <= n;k++)
notPrime[k*i] = true;
}
return res;
}
};