 # cjavdev's solution

## to Nth Prime in the Ruby Track

Published at Feb 07 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.

For installation and learning resources, refer to the Ruby resources page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

``````gem install minitest
``````

If you would like color output, you can `require 'minitest/pride'` in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

``````ruby nth_prime_test.rb
``````

To include color from the command line:

``````ruby -r minitest/pride nth_prime_test.rb
``````

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

### nth_prime_test.rb

``````require 'minitest/autorun'
require_relative 'nth_prime'

# Common test data version: 2.1.0 4a3ba76
class NthPrimeTest < Minitest::Test
def test_first_prime
# skip
assert_equal 2, Prime.nth(1)
end

def test_second_prime
skip
assert_equal 3, Prime.nth(2)
end

def test_sixth_prime
skip
assert_equal 13, Prime.nth(6)
end

def test_big_prime
skip
assert_equal 104743, Prime.nth(10001)
end

def test_there_is_no_zeroth_prime
skip
assert_raises(ArgumentError) do
Prime.nth(0)
end
end
end``````
``````class Prime
def self.nth(n)
raise ArgumentError if n <= 0
primes = []
i = 2
while primes.length < n
if Prime.is_prime?(primes, i)
primes << i
end
i += 1
end
primes.last
end

def self.is_prime?(primes, x)
primes.each do |prime|
# Return early if the number in question is evenly divisible by a prime.
return false if x != prime && x % prime == 0
end
true
end
end``````