ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Aug 26 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.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test`

in the exercise directory.

For more detailed info about the Scala track see the help page.

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

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

```
import org.scalatest.{Matchers, FunSuite}
/** @version 2.1.0 */
class NthPrimeTest extends FunSuite with Matchers {
test("first prime") {
NthPrime.prime(1) should be (Some(2))
}
test("second prime") {
pending
NthPrime.prime(2) should be (Some(3))
}
test("sixth prime") {
pending
NthPrime.prime(6) should be (Some(13))
}
test("big prime") {
pending
NthPrime.prime(10001) should be (Some(104743))
}
test("there is no zeroth prime") {
pending
NthPrime.prime(0) should be (None)
}
}
```

```
object NthPrime {
val primes: Stream[Int] = 2 #:: Stream.from(3, 2).filter(isPrime)
def isPrime(number: Int): Boolean =
primes.takeWhile(_ <= math.sqrt(number)).forall(number % _ != 0)
def prime(n: Int): Option[Int] = n match {
case 0 => None
case _ => Some(primes.take(n).last)
}
}
```

A huge amount can be learned from reading other peopleâ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

Level up your programming skills with 3,423 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments