Skip to content

Instantly share code, notes, and snippets.

@naush
Created March 11, 2012 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save naush/2016629 to your computer and use it in GitHub Desktop.
Save naush/2016629 to your computer and use it in GitHub Desktop.
module PrimeFactor
def self.new
@memoized = {}
Hash.new do |h, index|
@memoized[index] ||= memoize(h, index)
h[index] = @memoized[index]
end
end
def self.memoize(h, number)
divisor = 2
while divisor < number
while number % divisor == 0
number = number / divisor
return [divisor] + h[number]
end
divisor = divisor + 1
end
return [number] if number > 1
return []
end
end
describe PrimeFactor do
it "factors 1 through 9" do
@factors = PrimeFactor.new
(1..9).each { |number| @factors[number] }
@factors.should == {
1 => [],
2 => [2],
3 => [3],
4 => [2, 2],
5 => [5],
6 => [2, 3],
7 => [7],
8 => [2, 2, 2],
9 => [3, 3]
}
end
end
@paytonrules
Copy link

Have you tried it where prime factor contains the hash instead of inheriting?

@naush
Copy link
Author

naush commented Mar 11, 2012

I have gone that direction briefly, but it was slightly more verbose because you're essentially delegating to a hash. But that did get rid of the vexing inheritance. I think what I might try next time is to pass in PrimeFactor to Hash.new instead (ie., Hash.new { |h, index| PrimeFactor.of(h, index) }.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment