Friday, May 15, 2015

204 Count Primes

来源:Leetcode

原帖:https://leetcode.com/problems/count-primes/

题目:
Count the number of prime numbers less than a non-negative number, n

代码:
 class Solution {  
 public:  
   int countPrimes(int n) {  
     vector<bool> primes(n-1, true);  
     primes[0] = false;  
     int count = 0;  
     for (int i = 1; i < n-1; ++i) {  
       if (primes[i] == true) {  
         count++;  
         int num = (i+1)*2;  
         while (num < n) {  
           primes[num-1] = false;  
           num = num + i + 1;  
         }  
       }  
     }  
     return count;  
   }  
 };  


No comments:

Post a Comment