LeetCode204——count primes

方法还是有很多的,通过率很低,不过这题还是需要思考清楚,不然很容易t

class Solution {
public:
    int countPrimes(int n)
    {
        if(n == 0 || n == 1)
        {
            return 0;
        }
        int cnt = 0;
        bool* isPrime = new bool[n];
        for(int i = 2;i != n;++ i)
        {
            isPrime[i] = true;
        }
        for(int i = 2;i * i < n;++ i)
        {
            if(!isPrime[i])
            {
                continue;
            }
            for(int j = i * i;j < n;j += i)
            {
                isPrime[j] = false;
            }
        }
        for(int i = 2;i < n;++ i)
        {
            if(isPrime[i])
            {
                cnt ++;
            }
        }
        delete[] isPrime;
        isPrime = NULL;
        return cnt;
    }
};
原文地址:https://www.cnblogs.com/thewaytomakemiracle/p/5146093.html