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.
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
面slb的实习的时候就被问到了这个题
中心思想就是,从2的倍数开始,反复的将素数的倍数标记为非素数。
给定的一个素数p的倍数构成一个从p开始的序列,相邻元素之间的差值为p。这是筛法与一般方法的关键区别。
//http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
class Solution {
public:
int countPrimes(int n) {
if(n < 2)
return 0;
vector<int> isPrime(n,1);
isPrime[0] = 0;
isPrime[1] = 0;
int count = 0;
for(int i = 2;i<n;++i)
{
if(isPrime[i] == 1)
{
++count;
if(i>sqrt(n))
continue;
for(int j = i*i;j<n;j+=i)
{
isPrime[j] = 0;
}
}
}
return count;
}
};