Created
February 5, 2014 15:27
-
-
Save ScotterC/8826026 to your computer and use it in GitHub Desktop.
Find the largest prime factor of a number
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
def largest_prime_factor(number) | |
factors = factors_of(number) | |
factors.select do |f| | |
is_prime?(f) | |
end.max | |
end | |
def factors_of(number) | |
1.upto(Math.sqrt(number).ceil).each_with_object([]) do |i, factors| | |
if number % i == 0 | |
factors << i | |
factors << number / i | |
end | |
end | |
end | |
def is_prime?(number) | |
prime = number != 1 | |
2.upto(Math.sqrt(number).ceil).each do |i| | |
if number % i == 0 | |
prime = false | |
break | |
end | |
end | |
prime | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment