写在前面
- 练手题,
- 回忆知识点
题目详情
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7
ac代码
- 时间换空间
- 逐个判断是否非质
class Solution
{
public:
int countPrimes(int n)
{
int cnt = 0;
for(int i=2; i<n; i++)
if(isPrime(i))
cnt++;
return cnt;
}
bool isPrime(int n)
{
if(n==2 || n==3)
return true;
for(int i=2; i*i<=n; i++)
if(n%i==0)
return false;
return true;
}
};
- 空间换时间
- 判断非质数组,统一计数
-
vector<int>
数组初始化 -
count(res.begin(), res.end(), 1)
计算数组中目标值个数
- 剔除
2、3、5、7...
以后的倍数
class Solution {
public:
int countPrimes(int n) {
if(n < 3) return 0;
vector<int> res(n, 1);
res[0] = 0;
res[1] = 0;
for(int i = 2; i < sqrt(n); ++i){
if(res[i] != 1)
continue;
for(int j = i*2; j < n; j += i){
res[j] = 0;
}
}
int num = count(res.begin(), res.end(), 1);
return num;
}
};
- 参考文章
- LeetCode 204. Count Primes计数质数 (C++)