204. Count Primes

Description:

Count the number of prime numbers less than a non-negative number, n.

解法一

int countPrimes(int n) {
    if (n<=2) return 0;
    vector<bool> passed(n, false);
    int sum = 1;
    int upper = sqrt(n);
    for (int i=3; i<n; i+=2) {
        if (!passed[i]) {
            sum++;
            //avoid overflow
            if (i>upper) continue;
            for (int j=i*i; j<n; j+=i) {
                passed[j] = true;
            }
        }
    }
    return sum;
}
posted @ 2016-01-30 23:11  背锅侠  阅读(129)  评论(0编辑  收藏  举报