Skip to content

Instantly share code, notes, and snippets.

@sjmadsen
Created February 18, 2015 16:16
Show Gist options
  • Save sjmadsen/9d5b23aad5e49dc865c5 to your computer and use it in GitHub Desktop.
Save sjmadsen/9d5b23aad5e49dc865c5 to your computer and use it in GitHub Desktop.
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