1、数组 标记质数的倍数
int countPrimes(int n) {
if (n == 0 || n == 1 || n == 2)
return 0;
int ans = 0;
vector<int> v(n + 1);
for (int i = 2; i < n; i++) {
if (v[i] == 0) {
ans++;
for (int j = 1; j <= n / i; j++) {
v[j * i] = 1;
}
}
}
return ans;
}
时间:O(nloglogn) 空间:O(n)
2、减少重复
int countPrimes(int n) {
vector<int> primes;
vector<int> nums(n, 0);
for (int i = 2; i < n; i++) {
if (nums[i] == 0) {
primes.push_back(i);
}
int len = primes.size();
for (int j = 0; j < len && i * primes[j] < n; j++) {
nums[i * primes[j]] = 1;
if (i % primes[j] == 0)
break;
}
}
return primes.size();
}
时间:O(n) 空间:O(n)
参考力扣官方题解