Skip to content

Instantly share code, notes, and snippets.

@dustinbrownman
Created March 5, 2014 06:41
Show Gist options
  • Select an option

  • Save dustinbrownman/9362305 to your computer and use it in GitHub Desktop.

Select an option

Save dustinbrownman/9362305 to your computer and use it in GitHub Desktop.
A function to return the nth prime.
def is_prime(num)
(2...num).all? { |n| num % n != 0 }
end
def nth_prime(n)
prime_numbers = []
num = 1
until prime_numbers.length >= n
if is_prime(num)
prime_numbers.push(num)
end
num += 1
end
prime_numbers[-1]
end
require 'rspec'
require 'nthprime'
describe 'nth_prime' do
it 'returns 1 as the first prime number' do
nth_prime(1).should eq 1
nth_prime(0).should be_nil
end
it 'returns the nth prime number' do
nth_prime(7).should eq 13
nth_prime(3).should eq 3
nth_prime(10).should eq 23
end
end
describe 'is_prime' do
it 'checks if a number is prime' do
is_prime(13).should be_true
end
it 'returns false if it is not a prime' do
is_prime(4).should be_false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment