Last active
April 2, 2016 19:10
-
-
Save durrellchamorro/d8a596f528928c0c52690ecb25a2e96c to your computer and use it in GitHub Desktop.
Nth_Prime
This file contains 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
class Prime | |
def self.nth(nth_prime) | |
raise ArgumentError if nth_prime == 0 | |
return 2 if nth_prime == 1 | |
primes = [2,3] | |
5.step(by:2) do |potential_prime| | |
break if primes.size == nth_prime | |
primes << potential_prime if prime? potential_prime | |
end | |
primes.last | |
end | |
def self.prime?(potential_prime) | |
sqrt = Math.sqrt(potential_prime).round # I don't need to round here, but for some reason doing so makes it almost twice as fast. | |
result = 2.upto(sqrt) do |number| | |
return false if potential_prime % number == 0 | |
end | |
result == false ? false : true | |
end | |
end | |
# I could have defined #prime? as follows below, but then it would return 2 if the potential_prime was prime. | |
# Since 2 is truthy the method below will also work the way it needs to work in the #nth method, | |
# but it wouldn't make sense to call Prime.prime?(5) and have the number 2 returned so I would make | |
#prime? a private_class_method, but it seems like a waste to not be able to use #prime? on it's own so | |
# I added some extra lines to #prime? above so it will return true or false instead of 2 or false. | |
# I imagine it's probably better ruby to have a method ending with ? explictly return true or false | |
# instead of a truthy or falsey value as well. | |
def self.prime?(potential_prime) | |
sqrt = Math.sqrt(potential_prime).round | |
2.upto(sqrt) do |number| | |
return false if potential_prime % number == 0 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment