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)
原文地址:https://www.cnblogs.com/wxquare/p/5224693.html