204 Count Prime
Time : O(n * sqrt(n))
class Solution {
public int countPrimes(int n) {
int count = 0;
for (int i = 2; i < n; i++) {
if(isPrime(i)) {
count++;
}
}
return count;
}
public boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
厄拉多塞筛法,求一组质数,时间复杂度仅有O(nloglogn)
class Solution {
public int countPrimes(int n) {
boolean[] notPrime = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if (notPrime[i] == false) {
count++;
for(int j = 2; i * j < n; j++) {
notPrime[i * j] = true;
}
}
}
return count;
}
}