🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉 # SergiiVlasiuk's solution

## to Nth Prime in the Scala Track

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.

## 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.

### NthPrimeTest.scala

``````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)
}
}``````