leetcode——204.——Count Primes

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


class Solution {
public:
    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]){
        for (int j = i; j*i < n; j++) {
            isprime[j*i] = false;
        }
        }
    }
    int cnt = 0;
    for (int i = 2; i < n; i++) {
        if (isprime[i]) cnt++;
    }
    return cnt;
        
    }
};

你可能感兴趣的:(LeetCode,算法题)