【leetcode】Count Primes(easy)

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

思路:数质数的个数

开始写了个蛮力的,存储已有质数,判断新数字是否可以整除已有质数。然后妥妥的超时了(⊙v⊙)。

看提示,发现有个Eratosthenes算法找质数的,说白了就是给所有的数字一个标记,把质数的整数倍标为false,那么下一个没被标为false的数字就是下一个质数。

int countPrimes(int n) {
        if(n <= 2) return 0;
        bool * mark = new bool[n];
        fill_n(mark, n, true);

        int primesNum = 1;
        int curpos = 2;
        while(curpos < n)
        {
            //把当前质数的倍数标记为不是质数
            for(int i = 2 * curpos; i < n; i += curpos)
            {
                mark[i] = false;
            }

            //找下一个质数
            int i;
            for(i = curpos + 1; i < n && !mark[i]; ++i);
            if(i == n)
            {
                delete [] mark;
                return primesNum; //没有多余的质数 返回答案
            }
            else
            {
                curpos = i;
                primesNum++;
            }
        }
    }

别人写的C版本的:

int countPrimes(int n) {
    bool *pb = calloc(n-1,sizeof(bool));

    int ret_c=0;
    // idx 0 represent 2
    int idx=0;
    int pend=n-2;
    while(idx<pend){
        if(0==pb[idx]){
            ++ret_c;
            int op=idx;
            while(op<pend){
                pb[op]=1;
                op+=(idx+2);
            }
        } 
        ++idx;
    }
    free(pb);
    return ret_c;
}
原文地址:https://www.cnblogs.com/dplearning/p/4519011.html