Created
July 3, 2012 19:58
-
-
Save shostakovich/3042550 to your computer and use it in GitHub Desktop.
PrimeFactors Kata Second iteration
This file contains 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 PrimeFactors | |
def self.generate(number) | |
if number == 1 | |
[] | |
elsif number <= 3 | |
[number] | |
else | |
result = [] | |
Array((2..number / 2)).each do |i| | |
while(number % i).zero? do | |
number = number / i | |
result << i | |
end | |
end | |
result | |
end | |
end | |
end | |
describe PrimeFactors do | |
it "returns no prime factors of 1" do | |
PrimeFactors.generate(1).should be == [] | |
end | |
it "returns the factor 2 for 2" do | |
PrimeFactors.generate(2).should be == [2] | |
end | |
it "returns the factor 3 for 3" do | |
PrimeFactors.generate(3).should be == [3] | |
end | |
it "returns the factors 2,2 for 4" do | |
PrimeFactors.generate(4).should be == [2,2] | |
end | |
it "returns the factors 2,3 for 6" do | |
PrimeFactors.generate(6).should be == [2,3] | |
end | |
it "returns the factors 2,2,2 for 8" do | |
PrimeFactors.generate(8).should be == [2,2,2] | |
end | |
it "returns the factors 2,2,3,5,7 for 420" do | |
PrimeFactors.generate(420).should be == [2,2,3,5,7] | |
end | |
end |
Forked, refactored and proven wrong ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Second try on this Kata.. The first time it works ;)
There must be a more elegant want of doing this..