-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathincremental_sieve.java
More file actions
43 lines (29 loc) · 966 Bytes
/
incremental_sieve.java
File metadata and controls
43 lines (29 loc) · 966 Bytes
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
38
39
40
41
42
43
import java.util.*;
public class incremental_sieve {
public static List<Integer> generatePrimes(int limit) {
// generate primes using incremental sieve
HashMap<Integer, Integer> map = new HashMap<>();
List<Integer> primes = new ArrayList<>();
primes.add(2);
for (int num = 3; num <= limit; num++) {
if (!map.containsKey(num)) {
primes.add(num);
map.put(num * num, 2 * num);
} else {
int step = map.get(num);
map.remove(num);
int next = num + step;
while (map.containsKey(next)) {
next += step;
}
map.put(next, step);
}
}
return primes;
}
public static void main(String[] args) {
int limit = 50;
List<Integer> primes = generatePrimes(limit);
System.out.println(primes);
}
}