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.
class Solution {
public:
int countPrimes(int n) {
vector<bool> num(n - 1, true);
num[0] = false;
int res = 0, limit = sqrt(n);
for (int i = 2; i <= limit; ++i) {
if (num[i - 1]) {
for (int j = i * 2; j < n; j += i) {
num[j - 1] = false;
}
}
}
for (int j = 0; j < n - 1; ++j) {
if (num[j]) ++res;
}
return res;
}
};
public:
int countPrimes(int n) {
vector<bool> num(n - 1, true);
num[0] = false;
int res = 0, limit = sqrt(n);
for (int i = 2; i <= limit; ++i) {
if (num[i - 1]) {
for (int j = i * 2; j < n; j += i) {
num[j - 1] = false;
}
}
}
for (int j = 0; j < n - 1; ++j) {
if (num[j]) ++res;
}
return res;
}
};