# Albert-Wang-Hipmunk's solution

## to Nth Prime in the Kotlin Track

Published at Nov 05 2019 · 0 comments
Instructions
Test suite
Solution

Given a number n, determine what the nth prime is.

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

If your language provides methods in the standard library to deal with prime numbers, pretend they don't exist and implement them yourself.

## Setup

Go through the setup instructions for Kotlin to install the necessary dependencies:

https://exercism.io/tracks/kotlin/installation

## Making the test suite pass

Execute the tests with:

``````\$ gradlew test
``````

Use `gradlew.bat` if you're on Windows

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the `@Ignore` annotation.

## Source

A variation on Problem 7 at Project Euler http://projecteuler.net/problem=7

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### PrimeTest.kt

``````import org.junit.Test
import org.junit.Ignore
import org.junit.Rule
import org.junit.rules.ExpectedException
import kotlin.test.assertEquals

class PrimeTest {

@Rule
@JvmField
var expectedException: ExpectedException = ExpectedException.none()

@Test
fun firstPrime() {
assertEquals(2, Prime.nth(1))
}

@Ignore
@Test
fun secondPrime() {
assertEquals(3, Prime.nth(2))
}

@Ignore
@Test
fun sixthPrime() {
assertEquals(13, Prime.nth(6))
}

@Ignore
@Test
fun bigPrime() {
assertEquals(104743, Prime.nth(10001))
}

@Ignore
@Test
fun undefinedPrime() {
expectedException.expect(IllegalArgumentException::class.java)
expectedException.expectMessage("There is no zeroth prime.")

Prime.nth(0)
}

}``````
``````fun main(argv: Array<String>) {
println("start")
for (i in 1..5) {
println(Prime.nth(i))
}
println("end")
}

class Prime {
companion object {
private val maxNum = 500000
private val primeTable = (2..maxNum).map { i -> Pair(i, true) }.toMap().toMutableMap()
private val primateList = initPrimeList()

private fun initPrimeList(): List<Int> {
for (i in 2 .. Math.sqrt(maxNum.toDouble()).toInt()) {
if (primeTable[i] == true) {
for (j in (i+i) .. maxNum step i) {
primeTable[j] = false
}
}
}
return primeTable.filter { entry -> entry.value }.map { entry -> entry.key }.toList()
}

fun nth(n: Int): Int {
require(n >= 1) { "There is no zeroth prime."}
require(n <= primateList.size) { "index exceed prime table size" }
return primateList[n - 1]
}
}
}``````