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

 

 1 class Solution {
 2 public:
 3     int countPrimes(int n) {
 4         vector<bool> num(n-1,true);
 5         num[0]=false;
 6         int res=0;
 7         int limit=sqrt(n);
 8 
 9         for(int i=2;i<=limit;i++)
10         {
11             if(num[i-1])
12             {
13                for(int j=i*i;j<n;j+=i)
14                {
15                   num[j-1]=false;
16                }
17             }
18         }
19 
20         for(int j=0;j<n-1;j++)
21         {
22             if(num[j])
23                res++;
24         }
25 
26         return res;
27     }
28 };

 

posted on 2015-06-07 11:42  黄瓜小肥皂  阅读(130)  评论(0编辑  收藏  举报