LeetCode | Count Primes

Count Primes

 Total Accepted: 10553 Total Submissions: 56521My Submissions

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.










思路:求小于n值的质数个数,主要考查求质数的优化算法,相对简单。

class Solution {
public:
    int countPrimes(int n) {
       if(n<=2) return 0;
       else
       {
          int cnt=0;
          int *arr=new int[n+10];
          for(int i=0;i<=n+9;i++) arr[i]=0;
          for(int i=2;i<=n-1;i++)
          {
            if(!arr[i]){
                   cnt++;
            }
            for(int j=i*2;j<=n-1;j+=i)
            {
                   arr[j]=1;
            }
         }
           return cnt;
       }
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted on 2015-05-23 14:43  Tob__yuhong  阅读(103)  评论(0编辑  收藏  举报

导航