204. Count Primes

来源:互联网 发布:国税务网络学校 编辑:程序博客网 时间:2024/05/17 12:49

Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Subscribe to see which companies asked this question


计算素数的方法要掌握,记得外围的判断标准是 n/2+1

class Solution {public:    int countPrimes(int n) {        vector<int> v1(n,1);        for(int i=2;i<n/2+1;++i)        {                        for(int k=i+i;k<n;k+=i)            {                if(v1[k]==1)                v1[k]=0;            }        }        int sum=0;        for(int i=2;i<n;++i)        sum+=v1[i];        return sum;    }};


0 0