码迷,mamicode.com
首页 > 其他好文 > 详细

Count Primes

时间:2015-04-27 21:22:18      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

Hint: The number n could be in the order of 100,000 to 5,000,000.

C++实现代码:

#include<new>
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;

class Solution {
public:
    int countPrimes(int n) {
        bool *arr=new bool[n+1];
        memset(arr,true,n);
        int count=0;
        for(int i=2;i*i<=n;++i)
        {
            if(arr[i])
            {
                int j=i;
                while(j*i<=n)
                {
                    arr[i*j]=0;
                    ++j;
                }
            }
        }
        for(int i=2;i<n;++i)
        {
            if(arr[i])
                count++;
        }
        return count;
    }
};
int main()
{
    Solution s;
    cout<<s.countPrimes(499979)<<endl;
}

 

Count Primes

标签:

原文地址:http://www.cnblogs.com/wuchanming/p/4461301.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!