# [LeetCode] 204. Count Primes 质数的个数

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

Example 1:

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


Example 2:

Input: n = 0
Output: 0


Example 3:

Input: n = 1
Output: 0


Constraints:

• 0 <= n <= 5 * 106

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

class Solution {
public:
int countPrimes(int n) {
int res = 0;
vector<bool> prime(n, true);
for (int i = 2; i < n; ++i) {
if (!prime[i]) continue;
++res;
for (int j = 2; i * j < n; ++j) {
prime[i * j] = false;
}
}
return res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/204

Ugly Number II

Ugly Number

Perfect Squares

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

https://leetcode.com/problems/count-primes/discuss/57588/My-simple-Java-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2015-04-28 13:40  Grandyang  阅读(25415)  评论(3编辑  收藏  举报