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.
此方法效率很高。
1 class Solution { 2 public: 3 int countPrimes(int n) { 4 if(n <= 2) 5 { 6 return 0; 7 } 8 int count = 1; 9 bool flag = false; 10 bool hash[n] = {false}; 11 for (int i = 3; i < n; i+=2) 12 { 13 if(hash[i]==false) 14 { 15 ++count; 16 } 17 if(i>sqrt(n)) continue; 18 for(int j = i*i; j < n; j+=i) 19 { 20 hash[j] = true; 21 } 22 } 23 return count; 24 25 } 26 };