forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountPrimes.java
37 lines (31 loc) · 940 Bytes
/
CountPrimes.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// https://leetcode.com/problems/count-primes
// T: O(n log(log(n)))
// S: O(n)
public class CountPrimes {
public static int countPrimes(int number) {
boolean[] sieve = getSieve(number);
return numberOfPrimes(sieve);
}
private static int numberOfPrimes(boolean[] array) {
int count = 0;
for (boolean value : array) {
if (!value) count++;
}
return count;
}
private static boolean[] getSieve(int number) {
if (number < 2) {
return new boolean[0];
}
boolean[] sieve = new boolean[number];
sieve[0] = sieve[1] = true;
for (long index = 2 ; index < sieve.length ; index++){
if (!sieve[(int) index]) {
for (long j = index * index ; j < sieve.length ; j += index) {
sieve[(int) j] = true;
}
}
}
return sieve;
}
}