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

leetcode - Count Primes

时间:2015-04-27 18:10:59      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

leetcode - https://leetcode.com/problems/count-primes/

Q:

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.

 

class Solution {
public:
    int countPrimes(int n) {
        int count=0;
        if(n<2) return count;
        bool *num = new bool[n];
        for (int i=1; i<=n; i++)
            num[i]=1;
        int i=2;
        while(i*i<n){
            for(int idx=i*2;idx<n;idx=idx+i)
                num[idx]=0;
            do{
                i++;
            }
            while(i*i<n && num[i]==0);
        }
        for(int i=2; i<n; i++)
            if (num[i]==1) count++;
        return count;
    }
};

 

思路: 要用筛法:http://zh.wikipedia.org/wiki/%E5%9F%83%E6%8B%89%E6%89%98%E6%96%AF%E7%89%B9%E5%B0%BC%E7%AD%9B%E6%B3%95

筛去不是素数的。首先建立一个bool型数组,然后初始化为全1,即全为素数。然后找到第一个素数i(从2开始),如果i的平方没有超过n,那么从i的两倍开始,加一倍标记一下0(非素数)。然后对i自加,直到找到下一素数。重复上述过程。

注意题目中是小于n。

 

leetcode - Count Primes

标签:

原文地址:http://www.cnblogs.com/shnj/p/4460785.html

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