File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 3838 " luhn" ,
3939 " pig-latin" ,
4040 " linked-list" ,
41+ " nth-prime" ,
4142 " pascals-triangle"
4243 ],
4344 "deprecated" : [
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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 () {
8+ assertThat (Prime .nth (1 )).isEqualTo (2 );
9+ }
10+
11+ @ Test
12+ public void testSecondPrime () {
13+ assertThat (Prime .nth (2 )).isEqualTo (3 );
14+ }
15+
16+ @ Test
17+ public void testSixthPrime () {
18+ assertThat (Prime .nth (6 )).isEqualTo (13 );
19+ }
20+
21+ @ Test
22+ public void testBigPrime () {
23+ assertThat (Prime .nth (10001 )).isEqualTo (104743 );
24+ }
25+
26+ @ Test (expected = IllegalArgumentException .class )
27+ public void testUndefinedPrime () {
28+ Prime .nth (0 );
29+ }
30+ }
Original file line number Diff line number Diff line change @@ -13,6 +13,7 @@ include 'hexadecimal'
1313include ' hello-world'
1414include ' luhn'
1515include ' meetup'
16+ include ' nth-prime'
1617include ' nucleotide-count'
1718include ' octal'
1819include ' pangram'
You can’t perform that action at this time.
0 commit comments