204. Count Primes

https://leetcode.com/problems/count-primes/submissions/

Problem

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

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Solution

class Solution {
public:
    int countPrimes(int n) {
        if (n - 1 < 2) return 0;
        bool flag[n];
        int count = n - 2;
        memset(flag, 1, n);
        flag[0] = flag[1] = 0;
        for (int i = 2; i <= sqrt(n); ++i) {
            if (!flag[i]) continue;
            for (int j = i * i; j < n; j += i) {
                if (!flag[j]) continue;
                flag[j] = 0;
                --count;
            }
        }
        return count;
    }
};
  • #math

  • #important

Last updated

Was this helpful?