Skip to content

Instantly share code, notes, and snippets.

@mariapacana
Created May 15, 2013 21:51
Show Gist options
  • Save mariapacana/5587703 to your computer and use it in GitHub Desktop.
Save mariapacana/5587703 to your computer and use it in GitHub Desktop.
# require 'Math'
def is_prime?(num)
(2..Math.sqrt(num)).each { |factor| return false if num % factor == 0 }
true
end
def prime_factors(num)
primes_hash = {}
primes = []
#Setting up hash of prime factors
(2..Math.sqrt(num)).each do |factor|
primes_hash[factor] = (num % factor == 0) if is_prime?(factor)
end
# Looking in primes hash for potential factors
primes_hash.each do |factor, is_multiple|
primes << factor if is_multiple
end
primes
end
puts prime_factors(3).inspect # => [3]
puts prime_factors(6).inspect # => [2,3]
puts prime_factors(8).inspect # => [2,2,2]
puts prime_factors(25).inspect # => [5,5]
puts prime_factors(123123123).inspect # => [3, 3, 41, 333667]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment