Description:
Count the number of prime numbers less than a non-negative number, n
References:
分析:运用Sieve of Eratosthenes方法,首先筛掉2的倍数,然后筛掉3的倍数,5的倍数,7的倍数等。注意第二层循环的起点为i而不是1。运行时间312ms。想想该如何优化吧
1 class Solution { 2 public: 3 int countPrimes(int n) { 4 if(n < 2) return 0; 5 6 vector<bool> result(n, true); 7 for(int i = 2; i < sqrt(n); i++){ 8 if(result[i]){ 9 for(int j = i; i * j < n; j++) 10 result[i*j] = false; 11 } 12 } 13 int count = 0; 14 for(int i = 2; i < n; i++){ 15 if(result[i]) count++; 16 } 17 return count; 18 } 19 };