您的位置:首页 > 其它

[LeetCode]Count Primes

2016-03-26 10:51 274 查看
Description:

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

参考https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

class Solution {
public:
int countPrimes(int n) {
if(n<=2)
return 0;
vector<bool> isprime(n,true);
for(int i=3; i*i<n; i=i+2){
if(isprime[i]){
for(int j=i*i; j<n; j+=2*i){ //隔开n个乘积,跳过偶数还有优化
isprime[j] = false;

}
}
}
int count = 1;
for(int i=3; i<n; i+=2){
if(isprime[i]) count++;
}
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: