204. Count Primes
Posted dysjtu1995
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了204. Count Primes相关的知识,希望对你有一定的参考价值。
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 (C++):
int countPrimes(int n) {
int count = 0;
vector<bool> isPrime(n, false);
for (int i = 2; i < n; ++i) {
isPrime[i] = true;
}
for (int i = 2; i*i < n; ++i) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
for (int i = 2; i < n; ++i) {
if (isPrime[i]) ++count;
}
return count;
}
性能:
Runtime: 208 ms??Memory Usage: 6.6 MB
思路:
Solution (C++):
性能:
Runtime: ms??Memory Usage: MB
以上是关于204. Count Primes的主要内容,如果未能解决你的问题,请参考以下文章