-
-
Save rubysolo/1986435 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PrimeFactor | |
def initialize(number) | |
@factors = Fiber.new do | |
divisor = 2 | |
while divisor < number | |
while number % divisor == 0 | |
Fiber.yield divisor | |
number = number / divisor | |
end | |
divisor = divisor + 1 | |
end | |
Fiber.yield number if number > 1 | |
end | |
end | |
def next | |
@factors.resume | |
end | |
end | |
describe PrimeFactor do | |
it "factors 1" do | |
factors = PrimeFactor.new(1) | |
factors.next.should be_nil | |
end | |
it "factors 2" do | |
factors = PrimeFactor.new(2) | |
factors.next.should == 2 | |
end | |
it "factors 3" do | |
factors = PrimeFactor.new(3) | |
factors.next.should == 3 | |
end | |
it "factors 4" do | |
factors = PrimeFactor.new(4) | |
factors.next.should == 2 | |
factors.next.should == 2 | |
end | |
it "factors 5" do | |
factors = PrimeFactor.new(5) | |
factors.next.should == 5 | |
end | |
it "factors 6" do | |
factors = PrimeFactor.new(6) | |
factors.next.should == 2 | |
factors.next.should == 3 | |
end | |
it "factors 7" do | |
factors = PrimeFactor.new(7) | |
factors.next.should == 7 | |
end | |
it "factors 8" do | |
factors = PrimeFactor.new(8) | |
factors.next.should == 2 | |
factors.next.should == 2 | |
factors.next.should == 2 | |
end | |
it "factors 9" do | |
factors = PrimeFactor.new(9) | |
factors.next.should == 3 | |
factors.next.should == 3 | |
end | |
it "factors a large number" do | |
factors = PrimeFactor.new(2*3*5*7*11*13*17) | |
factors.next.should == 2 | |
factors.next.should == 3 | |
factors.next.should == 5 | |
factors.next.should == 7 | |
factors.next.should == 11 | |
factors.next.should == 13 | |
factors.next.should == 17 | |
end | |
# it "factors 1" do | |
# PrimeFactor.of(1).should == [] | |
# end | |
# it "factors 2" do | |
# PrimeFactor.of(2).should == [2] | |
# end | |
# it "factors 3" do | |
# PrimeFactor.of(3).should == [3] | |
# end | |
# it "factors 4" do | |
# PrimeFactor.of(4).should == [2, 2] | |
# end | |
# it "factors 5" do | |
# PrimeFactor.of(5).should == [5] | |
# end | |
# it "factors 6" do | |
# PrimeFactor.of(6).should == [2, 3] | |
# end | |
# it "factors 7" do | |
# PrimeFactor.of(7).should == [7] | |
# end | |
# it "factors 8" do | |
# PrimeFactor.of(8).should == [2, 2, 2] | |
# end | |
# it "factors 9" do | |
# PrimeFactor.of(9).should == [3, 3] | |
# end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment