【LeetCode & 剑指offer刷题】特殊数题3:204 Count Primes

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

204. Count Primes

Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
 
/*
问题:
    数素数(质数)的个数(小于n)
方法:
    Sieve of Eratosthenes solution
    用已经找到的质因子i去乘,去掉合数i^2, i^2+i, i^2+2i, i^2+3i, ..., not exceeding n
举例:
 n = 16(小于n,故不包含15,创建15长度,p[0]无用,直观一点,以1算起,下标与数对应)
 p[0] = p[1] = false
 2: 4 6 8 10 12 14
 3: 9 12 15 
 sqrt(16) = 4
 
*/
class Solution
{
public:
    int countPrimes(int n)
    {
        if(n <= 2) return 0;
        vector<bool> prime(n, true); //初始化为true
        prime[0] = prime[1] = false;
        for(int i = 2; i<sqrt(n); i++) //i = 2~sqrt(n)
        {
            if(prime[i])
            {
                for(int j=i*i; j<n; j+=i) prime[j] = false; //j = i^2, i^2+i, i^2+2i, i^2+3i, ..., not exceeding n,均不是质数
            }
        }
       
        return count(prime.begin(), prime.end(), true);
    }
};
/*
也可直接这样计数,比count函数更快
        int result = 0;
        for (int ii = 2; ii < n; ++ii)
        {
            if (is_prime[ii]) result++;
        }
*/
 
 

 

posted @ 2019-01-05 16:30  wikiwen  阅读(182)  评论(0编辑  收藏  举报