204. Count Primes

来源:互联网 发布:大数据架构基础 编辑:程序博客网 时间:2024/05/16 09:04

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

埃拉托色你筛选法

class Solution {public:    int countPrimes(int n) {        if(n < 2) return 0;        int cnt = n - 2;        vector<int> A(n);        for(int i = 2; i < n; ++i)            A[i] = i;        for(int p = 2; p * p < n; ++p){            if(A[p] != 0){                int j = p * p;                while(j < n){                    if(A[j] != 0)                        --cnt;                    A[j] = 0;                    j += p;                }            }        }        return cnt;    }};
0 0