题目:
Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Hint:
-
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity ofisPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?
最直观的想法是遍历2到n-1,同时用一张表存下来已经找到的质数,对用表中的每一个数去除当前数i,如果有能整除的,则i不是质数,如果都不能整除,则i是质数,把i放入表格,遍历完毕后,table中放的就是该小于n的所有质数,个数就是table的大小。这样做可以得到正确结果,但是超时(很久很久)。
class Solution {
public:
int countPrimes(int n) {
if (n <= 1) return 0;
vector<int> primes;//存放已经找到的所有质数
primes.push_back(2);
for (int i = 3; i < n; ++i){
int j = 0;
for (; j < primes.size(); ++j){
if (0 == i%primes[j]) break;
}
if (j == primes.size()) primes.push_back(i);
}
return primes.size();
}
};
解决该问题的一个巧妙的算法是Eratosthenes筛选算法,真是禁不住概叹 太TM妙了!
class Solution {
public:
int countPrimes(int n) {
if (n <= 1) return 0;
vector<bool> isPrime(n);//isPrime[i]表示整数i是否是质数
for (int i = 2; i < n ; ++i) isPrime[i] = true;//初始化isPrime
//对每一个质数i进行一下操作:从i*i开始,i的所有整数倍都不是质数
for (int i = 2; i * i < n; ++i){//!!!注意这里的循环结束条件是i*i < n
if (isPrime[i]){//i是整数
for (int j = i*i; j < n; j = j + i) isPrime[j] = false;
}
}
//统计质数个数
int res = 0;
for (int i = 2; i < n; ++i){
if (isPrime[i]) ++res;
}
return res;
}
};