-
Notifications
You must be signed in to change notification settings - Fork 2
/
Primes.java
53 lines (41 loc) · 1.33 KB
/
Primes.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.stream.IntStream;
import java.util.*;
public class Primes {
static List<Integer> knownPrimes = new ArrayList<Integer>();
public static IntStream stream() {
Map<String, Integer> metaData = new HashMap<>();
metaData.put("lastKnownPrimeIndex", 0);
return IntStream.generate( () -> next(metaData) );
}
public static int next(Map<String, Integer> metaData) {
int desiredPrimeIndex = metaData.get("lastKnownPrimeIndex") + 1;
while (knownPrimes.size() < desiredPrimeIndex) {
int lastKnownPrime = knownPrimes.size() > 0 ? knownPrimes.get(knownPrimes.size() - 1) : 1;
int nextPrime = getNextPrime(lastKnownPrime);
knownPrimes.add(nextPrime);
}
int desiredPrimeNum = knownPrimes.get(desiredPrimeIndex - 1);
metaData.put("lastKnownPrimeIndex", desiredPrimeIndex);
return desiredPrimeNum;
}
public static int getNextPrime(int start) {
int nextPrime = start + 1;
while (!isPrime(nextPrime)) {
nextPrime++;
}
return nextPrime;
}
public static Boolean isPrime(int potentialPrime) {
Boolean isPrime = true;
int upperBound = (int) Math.sqrt(potentialPrime);
for (Integer div : knownPrimes) {
if (div > upperBound) {
break;
}
if (potentialPrime % div == 0) {
return false;
}
}
return isPrime;
}
}