File tree Expand file tree Collapse file tree 1 file changed +14
-11
lines changed Expand file tree Collapse file tree 1 file changed +14
-11
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int countPrimes (int n ) {
3
- boolean [] isPrime = new boolean [n ];
4
- Arrays .fill (isPrime , true );
5
- for (int i = 2 ; i * i < n ; i ++) {
6
- if (isPrime [i ]) {
7
- for (int j = i * i ; j < n ; j += i ) {
8
- isPrime [j ] = false ;
3
+ if (n < 2 ) {
4
+ return 0 ;
5
+ }
6
+ int [] nums = new int [n ];
7
+ populateSieveArray (nums );
8
+ return (int ) Arrays .stream (nums ).boxed ().filter (e -> e != -1 ).count ();
9
+ }
10
+
11
+ private void populateSieveArray (int [] nums ) {
12
+ Arrays .fill (nums , 0 , 2 , -1 );
13
+ for (int i = 2 ; i < nums .length ; i ++) {
14
+ if (nums [i ] != -1 ) {
15
+ for (int j = i + i ; j < nums .length ; j += i ) {
16
+ nums [j ] = -1 ;
9
17
}
10
18
}
11
19
}
12
- int numOfPrimes = 0 ;
13
- for (int i = 2 ; i < n ; i ++) {
14
- numOfPrimes += isPrime [i ] ? 1 : 0 ;
15
- }
16
- return numOfPrimes ;
17
20
}
18
21
}
You can’t perform that action at this time.
0 commit comments