Skip to content

Commit f4c3051

Browse files
authored
Update Count Primes.java
1 parent ffbad56 commit f4c3051

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

Easy/Count Primes.java

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
11
class Solution {
22
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;
917
}
1018
}
1119
}
12-
int numOfPrimes = 0;
13-
for (int i = 2; i < n; i++) {
14-
numOfPrimes += isPrime[i] ? 1 : 0;
15-
}
16-
return numOfPrimes;
1720
}
1821
}

0 commit comments

Comments
 (0)