204. Count Primes(LeetCode)

Description:

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

 1 class Solution {
 2 public:
 3     int countPrimes(int n) {
 4       vector<bool> num(n - 1, true);
 5         num[0] = false;
 6         int res = 0, limit = sqrt(n);
 7         for (int i = 2; i <= limit; ++i) {
 8             if (num[i - 1]) {
 9                 for (int j = i * i; j < n; j += i) {
10                     num[j - 1] = false;
11                 }
12             }
13         }
14         for (int j = 0; j < n - 1; ++j) {
15             if (num[j]) ++res;
16         }
17         return res;
18     }
19 };
原文地址:https://www.cnblogs.com/wujufengyun/p/7193077.html