Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nistude/3045485 to your computer and use it in GitHub Desktop.
Save nistude/3045485 to your computer and use it in GitHub Desktop.
PrimeFactors Kata Second iteration
module PrimeFactors
def decompose(number)
if number <= 3
[number]
else
prime_factors = []
(2..number / 2).each do |prime|
while(number % prime).zero? do
number = number / prime
prime_factors << prime
end
end
prime_factors
end
end
end
describe PrimeFactors do
include PrimeFactors
it "returns the factor 1 for 1" do
decompose(1).should == [1]
end
it "returns the factor 2 for 2" do
decompose(2).should == [2]
end
it "returns the factor 3 for 3" do
decompose(3).should == [3]
end
it "returns the factors 2,2 for 4" do
decompose(4).should == [2,2]
end
it "returns the factor 5 for 5" do
decompose(5).should == [5]
end
it "returns the factors 2,3 for 6" do
decompose(6).should == [2,3]
end
it "returns the factors 2,2,2 for 8" do
decompose(8).should == [2,2,2]
end
it "returns the factors 2,2,3,5,7 for 420" do
decompose(420).should == [2,2,3,5,7]
end
end
@shostakovich
Copy link

Thats a nice way of doing it.. The tests read much nicer.

Yeah I thought about this problem with the number itself being prime and bigger 4 in bed..

I think it need a is_prime? method or so..

The main problem of this is really writing the right tests..

@shostakovich
Copy link

Here on line 21ff. Is 1 a prime factor of 1?

@nistude
Copy link
Author

nistude commented Jul 4, 2012 via email

@shostakovich
Copy link

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

http://en.wikipedia.org/wiki/Prime_number

Here is the link to project euler btw..

http://projecteuler.net/problems

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