forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrime.java
More file actions
42 lines (32 loc) · 850 Bytes
/
Prime.java
File metadata and controls
42 lines (32 loc) · 850 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
import java.util.stream.IntStream;
public final class Prime {
public static int nth(int nth) {
if (nth < 1) {
throw new IllegalArgumentException();
}
int primesFound = 0;
int possiblePrime = 1;
while (primesFound < nth) {
possiblePrime++;
if (isPrime(possiblePrime)) {
primesFound++;
}
}
return possiblePrime;
}
private static boolean isPrime(int n) {
if (n == 1) {
return false;
}
if (n == 2) {
return true;
}
boolean divisible = IntStream
.rangeClosed(2, (int) Math.ceil(Math.sqrt(n)))
.anyMatch((int i) -> n % i == 0);
if (divisible) {
return false;
}
return true;
}
}