Description:
Count the number of prime numbers less than a non-negative number, n
1 public class Solution { 2 public int countPrimes(int n) { 3 if(n <= 2) return 0; 4 boolean[] arr = new boolean[n];//use false to represent prime numbers 5 //Actually here only use 1 ~ n-1 6 int sqr = (int)Math.sqrt(n - 1); 7 for(int i = 2; i <= sqr; i ++){ 8 if(!arr[i]){ 9 for(int j = i * i; j < n; j += i){ 10 arr[j] = true; 11 } 12 } 13 } 14 int count = 0; 15 for(int i = 2; i < n; i ++){ 16 if(!arr[i]) count ++; 17 } 18 return count; 19 } 20 }
Another Solution:
1 public class Solution { 2 public int countPrimes(int n) { 3 if(n < 3) return 0; 4 HashSet<Integer> primes = new HashSet<Integer> (); 5 for(int i = 2; i < n; i ++){ 6 if(primes.isEmpty()){ 7 primes.add(i); 8 }else{ 9 Iterator it = primes.iterator(); 10 boolean isPrime = true; 11 while(it.hasNext()){ 12 Integer tmp = (Integer) it.next(); 13 if(i % tmp == 0) isPrime = false; 14 } 15 if(isPrime) primes.add(i); 16 } 17 } 18 return primes.size(); 19 } 20 }
This one return Time Limit Exceeded for case: 499979