We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ffbad56 commit f4c3051Copy full SHA for f4c3051
Easy/Count Primes.java
@@ -1,18 +1,21 @@
1
class Solution {
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;
+ if (n < 2) {
+ return 0;
+ }
+ int[] nums = new int[n];
+ populateSieveArray(nums);
+ 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;
17
}
18
19
- int numOfPrimes = 0;
- for (int i = 2; i < n; i++) {
- numOfPrimes += isPrime[i] ? 1 : 0;
- }
- return numOfPrimes;
20
21
0 commit comments