Skip to content

Instantly share code, notes, and snippets.

@kgthegreat
Created August 22, 2012 07:45
Show Gist options
  • Save kgthegreat/3423525 to your computer and use it in GitHub Desktop.
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
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