Count Primes

题目:

Description:

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

cpp:

class Solution {
public:
    int countPrimes(int n) {
        bool isPrime[n];
        for (int i = 0; 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;
            }
        }
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (isPrime[i])
                count++;
        }
        return count;
    }
};

python:

class Solution:
    # @param {integer} n
    # @return {integer}
    def countPrimes(self, n):
        isPrime = [True] * max(n, 2)
        isPrime[0], isPrime[1] = False, False
        x = 2
        while x * x < n:
            if isPrime[x]:
                p = x * x
                while p < n:
                    isPrime[p] = False
                    p += x
            x += 1
        return sum(isPrime)

 

posted @ 2016-02-28 14:20  wxquare  阅读(126)  评论(0编辑  收藏  举报