Skip to content

Instantly share code, notes, and snippets.

@mattknox
Created July 12, 2011 03:03
Show Gist options
  • Save mattknox/1077312 to your computer and use it in GitHub Desktop.
Save mattknox/1077312 to your computer and use it in GitHub Desktop.
class LcmFinder
attr_accessor :seen, :factors
def initialize
@seen = Set.new
@factors = Hash.new(0)
end
def factor(n)
cur = n
max = 2
fin = (n ** 0.5).ceil
factors_of_n = Hash.new(0)
while cur > 1
puts "cur=#{cur}, max=#{max}"
if 0 == (cur % max)
puts "multiple"
factors_of_n[max] += 1
@seen << cur
cur /= max
else
puts "not a multiple"
max += 1
end
end
return factors_of_n
end
def lcm(nums)
nums.sort.reverse.each do |n|
unless @seen.member?(n)
h = factor(n)
h.each do |k,v|
@factors[k] = [@factors[k], v].max
end
end
end
res = 1
@factors.each do |k,v|
res *= (k ** v)
end
puts @factors.inspect
puts @seen.inspect
res
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment