Created
August 22, 2012 07:45
-
-
Save kgthegreat/3423525 to your computer and use it in GitHub Desktop.
Finds the greatest prime factor of a number. Answer to http://projecteuler.net/problem=3
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 greatest_prime_factor(n) | |
divider = 2 | |
finder = n | |
factors = [] | |
while divider < finder | |
if n%divider == 0 | |
factors << divider | |
finder = finder/divider | |
factors << finder | |
end | |
if divider.even? | |
divider = divider + 1 | |
else | |
divider = divider + 2 | |
end | |
end | |
factors.sort {|x,y| y <=> x }.each do |factor| | |
return factor unless is_not_prime? factor | |
end | |
end | |
def is_not_prime?(n) | |
divider = 2 | |
while divider < n | |
return true if n%divider == 0 | |
divider = divider + 1 | |
end | |
return false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment