Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"luhn",
"pig-latin",
"linked-list",
"nth-prime",
"pascals-triangle"
],
"deprecated": [
Expand Down
12 changes: 12 additions & 0 deletions nth-prime/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
apply plugin: "java"
apply plugin: "eclipse"
apply plugin: "idea"

repositories {
mavenCentral()
}

dependencies {
testCompile "junit:junit:4.10"
testCompile "org.assertj:assertj-core:3.2.0"
}
Empty file.
42 changes: 42 additions & 0 deletions nth-prime/src/example/java/Prime.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
}
Empty file added nth-prime/src/main/java/.keep
Empty file.
Empty file added nth-prime/src/test/java/.keep
Empty file.
30 changes: 30 additions & 0 deletions nth-prime/src/test/java/PrimeTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class PrimeTest {
@Test
public void testFirstPrime() {
assertThat(Prime.nth(1)).isEqualTo(2);
}

@Test
public void testSecondPrime() {
assertThat(Prime.nth(2)).isEqualTo(3);
}

@Test
public void testSixthPrime() {
assertThat(Prime.nth(6)).isEqualTo(13);
}

@Test
public void testBigPrime() {
assertThat(Prime.nth(10001)).isEqualTo(104743);
}

@Test(expected = IllegalArgumentException.class)
public void testUndefinedPrime() {
Prime.nth(0);
}
}
1 change: 1 addition & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ include 'hexadecimal'
include 'hello-world'
include 'luhn'
include 'meetup'
include 'nth-prime'
include 'nucleotide-count'
include 'octal'
include 'pangram'
Expand Down