Skip to content

Commit deed8dd

Browse files
committed
Add nth-prime exercise
Tests and example implementation based on the ruby exercise. Completes a task for exercism#3.
1 parent fec9c6b commit deed8dd

File tree

7 files changed

+86
-1
lines changed

7 files changed

+86
-1
lines changed

config.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@
3737
"octal",
3838
"luhn",
3939
"pig-latin",
40-
"pascals-triangle"
40+
"pascals-triangle",
41+
"nth-prime"
4142
],
4243
"deprecated": [
4344
],

nth-prime/build.gradle

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
apply plugin: "java"
2+
apply plugin: "eclipse"
3+
apply plugin: "idea"
4+
5+
repositories {
6+
mavenCentral()
7+
}
8+
9+
dependencies {
10+
testCompile "junit:junit:4.10"
11+
testCompile "org.assertj:assertj-core:3.2.0"
12+
}

nth-prime/src/example/java/.keep

Whitespace-only changes.

nth-prime/src/example/java/Prime.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.stream.IntStream;
2+
3+
public final class Prime {
4+
public static int nth(int nth) {
5+
if (nth < 1) {
6+
throw new IllegalArgumentException();
7+
}
8+
9+
int primesFound = 0;
10+
int possiblePrime = 1;
11+
12+
while (primesFound < nth) {
13+
possiblePrime++;
14+
15+
if (isPrime(possiblePrime)) {
16+
primesFound++;
17+
}
18+
}
19+
20+
return possiblePrime;
21+
}
22+
23+
private static boolean isPrime(int n) {
24+
if (n == 1) {
25+
return false;
26+
}
27+
28+
if (n == 2) {
29+
return true;
30+
}
31+
32+
boolean divisible = IntStream
33+
.rangeClosed(2, (int) Math.ceil(Math.sqrt(n)))
34+
.anyMatch((int i) -> n % i == 0);
35+
36+
if (divisible) {
37+
return false;
38+
}
39+
40+
return true;
41+
}
42+
}

nth-prime/src/main/java/.keep

Whitespace-only changes.

nth-prime/src/test/java/.keep

Whitespace-only changes.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import org.junit.Test;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
public class PrimeTest {
6+
@Test
7+
public void testFirstPrime() throws Exception {
8+
assertThat(Prime.nth(1)).isEqualTo(2);
9+
}
10+
11+
@Test
12+
public void testSecondPrime() throws Exception {
13+
assertThat(Prime.nth(2)).isEqualTo(3);
14+
}
15+
16+
@Test
17+
public void testSixthPrime() throws Exception {
18+
assertThat(Prime.nth(6)).isEqualTo(13);
19+
}
20+
21+
@Test
22+
public void testBigPrime() throws Exception {
23+
assertThat(Prime.nth(10001)).isEqualTo(104743);
24+
}
25+
26+
@Test(expected = IllegalArgumentException.class)
27+
public void testUndefinedPrime() throws Exception {
28+
Prime.nth(0);
29+
}
30+
}

0 commit comments

Comments
 (0)