Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compute the prime factors of a number
class PrimeFactors
def self.of(n)
factors(n).compact.reject { |x| !is_prime?(x) }
end
def self.factors(n)
return [1] if n == 1
(1..n / 2).map { |divisor| (n % divisor) == 0 ? divisor : nil }
end
def self.is_prime?(n)
factors(n).compact == [1]
end
end
number = ARGV.shift.to_i
puts "Prime factors of #{number} are #{PrimeFactors.of(number).inspect}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.