题目描述
Description:
Count the number of prime numbers less than a non-negative number, n
题目分析
本题求小于n(n为大于零的数)的质数个数。
方法一
int countPrimes1(int n)
{
int count=0;
bool flag=1;
for (int i=2;i<n;i++)
{
for (int j=2;j<sqrt(i*1.0);j++ )
{
if (i%j==0)
{
flag=0;
}
}
if (flag) count++;
}
return count;
}
这种是最普通直接的方法,但是效率太低,当n较大的时候,会出现
Time Limit Exceeded
方法二
利用埃拉托斯特尼筛法Sieve of Eratosthenes,这个算法的过程如下图所示,我们从2开始遍历到根号n,先找到第一个没有被标记的数2,然后将其所有的倍数全部标记出来,然后到下一个没有被标记的数3,标记其所有倍数,一次类推,直到根号n,此时数组中未被标记的数字就是质数。我们需要一个n长度的bool型数组来记录每个数字是否被标记,数组每个下标表示其值,长度为n的原因是题目说是小于n的质数个数,即最大数为n-1,并不包括n。 然后我们用两个for循环来实现埃拉托斯特尼筛法,难度并不是很大,代码如下所示:
int countPrimes(int n)
{
vector<bool> a(n,0);
a[0]=1;
a[1]=1;
for (int i=2;i*i<n;i++)
{
if (!a[i])
{
for (int j=i;i*j<n;j++)
{
a[i*j]=1;
}
}
}
int count=0;
count=accumulate(a.begin(),a.end(),0);
return n-count;
}
完整代码如下:
#include <iostream>
#include <vector>
#include <numeric>
#include <math.h>
using namespace std;
int countPrimes(int n);
int countPrimes1(int n);
void main()
{
int n=4;
cout<<countPrimes(n)<<endl;
cout<<countPrimes1(n);
}
int countPrimes(int n)
{
vector<bool> a(n,0);
a[0]=1;
a[1]=1;
for (int i=2;i*i<n;i++)
{
if (!a[i])
{
for (int j=i;i*j<n;j++)
{
a[i*j]=1;
}
}
}
int count=0;
count=accumulate(a.begin(),a.end(),0);//求a中被标记的数的个数
return n-count;
}
int countPrimes1(int n)
{
int count=0;
bool flag=1;
for (int i=2;i<n;i++)
{
for (int j=2;j<sqrt(i*1.0);j++ )
{
if (i%j==0)
{
flag=0;
}
}
if (flag) count++;
}
return count;
}