Count the number of prime numbers less than a non-negative number, n.
Answer:
Method 1. Judge using isPrime for every 4 -- (n-1), O(n2).
public class Solution {
public int countPrimes(int n) {
n--;
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(2);
primes.add(3);
for(int i=5;i<=n;i=i+2){
Boolean isPrime = true;
for(Integer prime : primes){
int max = (int)Math.sqrt(n);
if(prime <= max){
if(n % prime == 0){
isPrime = false;
}
}
}
if(isPrime == true){
primes.add(i);
}
}
return primes.size();
}
}
Time Limit Exceeded : 1500000
Method 2. "Sieze of Eratosthenes" https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
public int countPrimes(int n) {
if (n <= 2)
return 0;
// init an array to track prime numbers
boolean[] primes = new boolean[n];
for (int i = 2; i < n; i++){
primes[i] = true;
}
for (int i = 2; i <= Math.sqrt(n - 1); i++) {
if (primes[i]) {
for (int j = i + i; j < n; j += i){
primes[j] = false;
}
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (primes[i])
count++;
}
return count;
}
No comments:
Post a Comment