leetcode-countPrimes

题目描述

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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值