The idea is very simple. instead of find each primes, remove all composite numbers from 2~n.

```
public class Solution {
public int countPrimes(int n) {
boolean[] exist = new boolean[n];
Arrays.fill(exist, true);
for (int i = 2; i < n; i++) {
if (exist[i]) {
int idx = i;
for (int j = 2; idx * j < n; j++) {
exist[idx*j] = false;
}
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (exist[i]) {
count++;
}
}
return count;
}
```

}