您的位置:首页 > 其它

leetcode-204. Count Primes

2016-04-27 21:54 253 查看
Description:

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

Credits:

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

Hint:

Let’s start with a isPrime function. To determine if a >number is prime, we need to check if it is not divisible by >any number less than n. The runtime complexity of >isPrime function would be O(n) and hence counting the >total prime numbers up to n would be O(n2). Could we >do better?

As we know the number must not be divisible by any >number > n / 2, we can immediately cut the total >iterations half by dividing only up to n / 2. Could we still >do better?

思路:如果用传统的从下往上遍历依次判断,数字大了显然不行。改进方法:空间换时间,给n个数设标志位,从小的开始依次乘积改标志位。直接看代码吧:

class Solution {
//传统的遍历判断是否是素数效率太低了,只能用空间换时间
public:
int countPrimes(int n) {
vector<bool> isPrime(n+1,true);
int primeNum = 0;
int upperBound = sqrt(n);
for(int i=2;i<n;i++)
{
if(isPrime[i])
{
primeNum++;

if(i > upperBound)
{
continue;
}
//小于n的能组合分解的都为合数
for(int j = i;i*j < n;j++)
{
isPrime[i*j] = false;
}
}
}
return primeNum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: