leetcode 204题求素数个数

   


Description:

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

 

提示晒数法:

http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

https://primes.utm.edu/howmany.html

 

别人的代码:

 

int countPrimes(int n) {
    if (n<=2) return 0;
    vector<bool> passed(n, false);
    int sum = 1;
    int upper = sqrt(n);
    for (int i=3; i<n; i+=2) {
        if (!passed[i]) {
            sum++;
            //avoid overflow
            if (i>upper) continue;
            for (int j=i*i; j<n; j+=i) {
                passed[j] = true;
            }
        }
    }
    return sum;
}

 

 

 

我的代码:

 

// countprime.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <iostream>
#include <math.h>
#include<vector>
using namespace std;

int countPrimes1(int n) 
{
	int temp = 0;
	if (2 >= n) return 0;

	bool* primes = new bool[n];
	for (int i = 2; i < n; ++i)
		primes[i] = true;

	int sqr = (int)(sqrt((double)(n - 1)));
	for (int i = 2; i <= sqr; ++i)
	{
		if (primes[i])
		{
			temp++;
			for (int j = i * i; j < n; j += i)
				primes[j] = false;
		}
	}

	int sum = 0;
	for (int i = 2; i < n; ++i)
		sum += (primes[i]) ? 1 : 0;

	/*cout<<temp;*/
	delete[] primes;

	return sum;
}


int countPrimes(int n)
{
	if (n<=2)return 0;

	int sum = 0;
	int sqr = (int)(sqrt((double)(n - 1)));

	vector<bool> prime(n,0);

	for(int i = 2; i < n; ++i)
		prime[i] = 1;

	for(int i =2; i <= sqr; ++i)
	{
		if(prime[i]==1)
		{
			//sum++;
			for(int j = i*i; j < n; j = j+i)
				prime[j] = 0;
		}

	}

	for(int i = 2;i < n; ++i)
		sum += prime[i] ? 1 : 0;


	return sum;
}

int _tmain(int argc, _TCHAR* argv[])
{
	


	cout<<countPrimes(5)<<endl;
	
	cout<<countPrimes1(3)<<endl;

	getchar();
	return 0;
}



超时代码:

 

int countPrimes(int n)
    {
        int sum = 0;
        for(int i = 0 ;i<=n;i=i+2)
        {
            int j = 2;
            int temp = sqrt(i);
            for(;j<=temp;j=j+1)
            {
                if((i%temp)==0)
                {break;}
                sum++;
            }
        }
            
        
        return sum;
    }

纪念一下首次AC

 


posted @ 2017-11-17 22:28  wangyaning  阅读(114)  评论(0编辑  收藏  举报