Skip to content

Instantly share code, notes, and snippets.

@ScotterC
Created February 5, 2014 15:27
Show Gist options
  • Save ScotterC/8826026 to your computer and use it in GitHub Desktop.
Save ScotterC/8826026 to your computer and use it in GitHub Desktop.
Find the largest prime factor of a number
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