204. Count Primes

来源:互联网 发布:send to kindle mac 编辑:程序博客网 时间:2024/05/21 22:58

Description:

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

本以为是个求素数的大水题,想都没想直接写了下面代码,结果直接TLE。

class Solution {public:    int countPrimes(int n) {        if(n<2)return 0;        int ans=0;        for(int i=2;i<=n;i++){            bool fla=1;            for(int j=2;j*j<=i;j++){                if(i%j==0){                    fla=0;                    break;                }            }            if(fla)ans++;        }        return ans;    }};
好吧,记得看过一个筛选法求素数的方法。查了下,它的时间复杂度为nloglogn,

于是写出下面代码然后顺利通过。

class Solution {public:    int countPrimes(int n) {        vector<bool> prim(n,true);        for(int i=2;i<=sqrt(n);i++){            if(prim[i]){                for(int j=i*i;j<=n;j+=i){                    prim[j]=false;                }            }        }        int ans=0;        for(int i=2;i<n;i++){            if(prim[i])ans++;        }        return ans;    }};



0 0