204. Count Primes

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以内的素数

 

C++(31ms):

 1 class Solution {
 2 public:
 3     int countPrimes(int n) {
 4         if (n <= 2)
 5             return 0 ;
 6         vector<bool> prime(n,true) ;
 7         int sum = 0 ;
 8         for(int i = 2 ; i < n ; i++){
 9             if (prime[i]){
10                 sum++ ;
11                 if (i > sqrt(n))
12                     continue ;
13                 for(int j = i * i ; j < n ; j += i){
14                     prime[j] = false ;
15                 }
16             }
17         }
18         return sum ;
19     }
20 };

 

posted @ 2018-03-21 15:05  __Meng  阅读(95)  评论(0编辑  收藏  举报