Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Forked from naush/prime_factor_spec.rb
Created March 11, 2012 15:11
Show Gist options
  • Select an option

  • Save JoshCheek/2016769 to your computer and use it in GitHub Desktop.

Select an option

Save JoshCheek/2016769 to your computer and use it in GitHub Desktop.
class PrimeFactor
attr_accessor :all_factors
def largest_divisor_less_than(number)
divisor = 2
while divisor <= Math.sqrt(number)
return number / divisor if number % divisor == 0
divisor = divisor + 1
end
return 1
end
def initialize
self.all_factors = Hash.new do |h, index|
number = index
divisor = largest_divisor_less_than(number)
if divisor == 1
factors = []
factors << number if number > 1
h[index] = factors
else
number = number / divisor
h[index] = [number] + h[divisor]
end
end
end
def [](number)
all_factors[number]
end
end
describe PrimeFactor do
factor = PrimeFactor.new
{ 1 => [],
2 => [2],
3 => [3],
4 => [2, 2],
5 => [5],
6 => [2, 3],
8 => [2, 2, 2],
12 => [2,2,3],
16 => [2, 2, 2, 2],
18 => [2, 3, 3],
24 => [2, 2, 2, 3],
(2*2*3*3) => [2, 2, 3, 3],
(2*3*3*5*5*5*11*17) => [2, 3, 3, 5, 5, 5, 11, 17]
}.each do |number, factors|
example("#{number} => #{factors.inspect}") { factor[number].should == factors }
end
end
@naush
Copy link
Copy Markdown

naush commented Mar 11, 2012

Nice working around inheritance.

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