Created
March 5, 2014 06:41
-
-
Save dustinbrownman/9362305 to your computer and use it in GitHub Desktop.
A function to return the nth prime.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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