Skip to content

Instantly share code, notes, and snippets.

@carbonphyber
Created April 30, 2011 19:23
Show Gist options
  • Save carbonphyber/949910 to your computer and use it in GitHub Desktop.
Save carbonphyber/949910 to your computer and use it in GitHub Desktop.
Ruby function to detect the factors of a Fixednum.
# @author David Wortham <djwortham+programming@gmail.com>
# @date 2011-04-30
# @license MIT License: http://www.opensource.org/licenses/mit-license.php
def factorize(input)
remainingInput = input
factors = {}
i = 2
while i <= remainingInput
while remainingInput % i == 0
if factors[i] == nil
factors[i] = 1
else
factors[i] = factors[i] + 1
end
remainingInput = remainingInput / i
end
i = i + 1
end
return factors
end
# usage:
# allFactors = factors(12345)
# tip: reassemble factors:
# product = 1
# allFactors.each{|factor, times| product = product * (factor ** times)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment