204. Count Primes

原文题目:

204. Count Primes

读题:

题目很简单,就是求小于n的质数的个数,注意是小于n,不等于n,也就是说n=2的时候,返回0,n=3时才是返回1

一下列出两种方法,一种方法超时,另一种方法逐步优化到46ms

//超时
class Solution 
{
public:
	int countPrimes(int n) 
	{
		int count = 0;
		int i = 0;
		if (n < 2)
		{
			return count;
		}
		for(i = 2;i<n;i++)
		{
			if(isPrime(i))
			{
				count++;
			}
		}
		return count;

	}
	int isPrime(int m)
	{
		int i = 0;
		if(m <2)
		{
			return 0;
		}
		for(i = 2;i <= m/2;i++)
		{
			if(m %i == 0)
			{
				return 0;
			}
		}
		return 1;
	}
};
//129ms
class Solution 
{
public:
	int countPrimes(int n) 
	{
		int count = 0;
		int i = 0;
		vector<bool> isprime;
		for (int i = 0; i < n; i++)
			isprime.push_back(true);

		for (int i = 2; i < n; i++)
		{
			for (int j = i + i; j < n; j += i)
			{
				isprime[j] = false;
			}
		}

		for (int i = 2; i < n; i++)
		{
			if (i != 0 && i != 1 && isprime[i])
				count++;
		}

		return count;
	}
};

//73ms
class Solution 
{
public:
	int countPrimes(int n) 
	{
		int count = 0;
		int i = 0;
		if(n <3)
		{
			return 0;
		}
		if(n == 3)
		{
			return 1;
		}
		if(n == 4)
		{
			return 2;
		}
		vector<bool> isprime;
		for (int i = 0; i < n; i++)
			isprime.push_back(true);

		for (int i = 2; i*i < n; i++)
		{
			for (int j = i + i; j < n; j += i)
			{
				isprime[j] = false;
			}
		}

		for (int i = 2; i < n; i++)
		{
			if (isprime[i])
				count++;
		}

		return count;
	}
};

//46ms
class Solution 
{
public:
	int countPrimes(int n) 
	{
		int count = 0;
		int i = 0;
		if(n <3)
		{
			return 0;
		}
		if(n == 3)
		{
			return 1;
		}
		if(n == 4)
		{
			return 2;
		}
		vector<bool> isprime;
		for (int i = 0; i < n; i++)
			isprime.push_back(true);

		for (int i = 2; i*i < n; i++)
		{
			if(isprime[i])
			{
				for (int j = i + i; j < n; j += i)
				{
					isprime[j] = false;
				}
			}
			
		}

		for (int i = 2; i < n; i++)
		{
			if (isprime[i])
				count++;
		}

		return count;
	}
};

  

原文地址:https://www.cnblogs.com/xqn2017/p/8006790.html