LeetCode204——Count Primes

Description:

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

Credits: Special thanks to @mithmatt for adding this problem and creating all test cases.

实现:

int countPrimes(int n) {
    bool *isprime = new bool[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 cnt = 0;
    for (int i = 2; i < n; i++) {
        if (isprime[i]) cnt++;
    }
    return cnt;
}

你可能感兴趣的:(LeetCode,素数)