leetcode - Count Primes

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++;
     delete []num;
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。

 

posted @ 2015-04-27 17:32  cnblogshnj  阅读(142)  评论(0)    收藏  举报