您的位置:首页 > 其它

【算法作业7】LeetCode 204. Count Primes

2017-04-08 11:08 746 查看
204. Count Primes

Description:

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

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?

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
题解:

本题是求小于一个非负整数n的所有质数的数目。第一反应想到的就是最简单粗暴的写一个判断质数的isPrime函数,然后对所有小于n的整数进行判断。但这种算法的复杂度为O(n²),肯定有时间限制不能通过。于是我们可以使用埃拉托色尼筛法,算法的主要思想就是让它在判断一个数为质数的同时,把它所有的倍数都设置为不是质数,这样就可以大大减少循环的次数。首先设置了一个vector来存放其下标对应的数字是否为质数并将除了0和1以外的其他元素设为true,在第一次循环的时候只需要循环到根号n,在这个循环中将每一个质数的倍数设为false即可。下面这幅图是从维基百科埃拉托色尼筛法中复制过来的,非常生动形象地诠释了算法的思想。



代码:

#include <cmath>
class Solution {
public:
int countPrimes(int n) {
vector<bool> primes;
if (n == 0)
primes.push_back(false);
else
{
for (int i = 0; i < n; i++)
{
primes.push_back(true);
}
primes[0] = false;
primes[1] = false;
}
for (int i = 0; i < sqrt(n); i++)
{
if (primes[i] == true)
{
for (int j = i * i; j < n; j += i)
{
primes[j] = false;
}
}
}
int count = 0;
for (int i = 0; i < n; i++)
{
if (primes[i])
count++;
}
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: