Exercism v3 launches on Sept 1st 2021. Learn more! 🚀🚀🚀
Avatar of kwaghmode

kwaghmode's solution

to Nth Prime in the Kotlin Track

Published at Oct 18 2019 · 0 comments
Test suite

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.


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


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.


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.


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

class PrimeTest {

    var expectedException: ExpectedException = ExpectedException.none()

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

    fun secondPrime() {
        assertEquals(3, Prime.nth(2))

    fun sixthPrime() {
        assertEquals(13, Prime.nth(6))

    fun bigPrime() {
        assertEquals(104743, Prime.nth(10001))

    fun undefinedPrime() {
        expectedException.expectMessage("There is no zeroth prime.")


object Prime {

    private val cachedPrimes = mutableSetOf(2)

    private fun generatePrimeSequence(start: Int) = generateSequence(start) { it + 1 }.filter { it.isPrime() }

    fun nth(num: Int): Int {
        require(num > 0) { "There is no zeroth prime." }
        val cachedPrimeSize = cachedPrimes.size
        if (cachedPrimeSize < num) {
            generatePrimeSequence(cachedPrimes.last() + 1).take(num - cachedPrimeSize).forEach { cachedPrimes.add(it) }
        return cachedPrimes.elementAt(num - 1)

    private fun Int.isPrime() = !(2 until this).any { this.rem(it) == 0 }


Community comments

Find this solution interesting? Ask the author a question to learn more.

kwaghmode's Reflection

I was caching to be part of sequence but also/piping support is not there so I have use explicitly forEach for add data in cache.If anyone knows better way of caching please comment