埃拉托斯特尼筛法(Sieve of Eratosthenes)简单c实现

来源:互联网 发布:淘宝争议处理规则 编辑:程序博客网 时间:2024/06/11 22:20

leetcode上的一道题目https://leetcode.com/problems/count-primes/
是关于数素数个数的。
然后根据提示查了下wiki
虽然中文版与英文版出入比较大,但基本上算说清楚了。

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;}

感觉还是挺巧妙的一个算法。上面为了省点内存做了个偏移。用idx0代表了素数2
算法的细节wiki已经解释得很详细了。
一句话就是每找到一个素数就把所有素数倍数的数标记为非素数,然后继续找没被标记的数。

0 0