Solution 1
这个题是我栽过坑的,一定要好好学习!
最简单的枚举方法,根据给定的数字从2一直枚举判定。
但是判定这里不需要也不能试遍所有数字(2次复杂度,会TLE),可以将这个范围缩小到 n \sqrt n n,这样就可以了。
但是目前这个方法因为题目范围修改已经被判定TLE了,因此只能进一步优化了
- 时间复杂度: O ( n n ) O(n \sqrt n) O(nn),其中 n n n为输入的数字,枚举和判定
- 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个状态量
class Solution {
public:
int countPrimes(int n) {
int ans = 0;
// 逐个枚举判定
for (int i = 2; i < n; i++) {
if (checkPrime(i)) { ans++; }
}
return ans;
}
private:
bool checkPrime(int x) {
for (int i = 2; i * i <= x; i++) {
if (x % i == 0) { return false; }
}
return true;
}
};
Solution 2
埃氏(Eratosthenes)筛,基于观察:当 x x x为质数,其任意多倍数 a x ax ax必为合数,预先标记尽可能多的数字,以减少实际判定质数的次数。同时我们可以继续优化,从 x 2 x^2 x2开始标记以尽可能减少标记的次数,因此其更小的倍数 a x ax ax已经会在 a a a的标记轮次中被标记到。
此外,对埃氏筛还有进一步优化的线性筛,这个等以后有用的时候再进一步学习了。
- 时间复杂度: O ( n log log n ) O(n\log \log n) O(nloglogn),其中 n n n为输入的数字,这个结果需要复杂证明,故略,同时可以看到明显比枚举小
- 空间复杂度: O ( n ) O(n) O(n),其中 n n n为输入的数字,典型的时间换空间的案例
class Solution {
public:
int countPrimes(int n) {
int ans = 0;
// 埃氏筛
vector<bool> isPrime(n, true);
for (int i = 2; i < n; i++) {
if (isPrime[i]) {
ans++;
if ((long long) i * i < n) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
}
}
return ans;
}
};
Solution 4
Solution 2的Python实现
class Solution:
def countPrimes(self, n: int) -> int:
ans = 0
isPrime = [True] * n
for i in range(2, n):
if isPrime[i]:
ans += 1
if i ** 2 < n:
for j in range(i**2, n, i):
isPrime[j] = False
return ans