Skip to content

Commit

Permalink
implement number factorization
Browse files Browse the repository at this point in the history
  • Loading branch information
aamyot authored and aamyot committed Jul 2, 2015
1 parent 2e9fd63 commit 552a382
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 10 deletions.
2 changes: 1 addition & 1 deletion app/controller/primes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def decompose(input)
if !(Integer(input) rescue false)
PrimeResults::NotANumber.new(input)
else
PrimeResults::Valid.new(input, PrimeFactors.factorsOf(input.to_i))
PrimeResults::Valid.new(input, PrimeFactors.of(input.to_i))
end
end

Expand Down
12 changes: 7 additions & 5 deletions app/primes/prime_factors.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
class PrimeFactors

def self.factorsOf(number)
def self.of(number)
primes = []

if number > 1
while number % 2 == 0
primes << 2
number /= 2
candidate = 2
while number > 1
while number % candidate == 0
primes << candidate
number /= candidate
end
candidate += 1
end

primes
Expand Down
12 changes: 12 additions & 0 deletions spec/challenges/prime_factors_challenge_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,16 @@ def app
'}')
end

it "decomposes a positive integer into prime factors" do
get "/primeFactors?number=300"

expect(last_response.status).to eq(200)
expect(last_response.content_type).to eq("application/json")
expect(last_response.body).to eq(
'{' \
'"number":300,' \
'"decomposition":[2,2,3,5,5]' \
'}')
end

end
16 changes: 12 additions & 4 deletions spec/primes/prime_factors_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,27 @@
RSpec.describe "Prime Factors" do

it 'returns empty for number lower than 2' do
expect(PrimeFactors.factorsOf(1)).to be_empty
expect(PrimeFactors.of(1)).to be_empty
end

it 'decomposes 2' do
expect(PrimeFactors.factorsOf(2)).to eq [2]
expect(PrimeFactors.of(2)).to eq [2]
end

it 'decomposes 4' do
expect(PrimeFactors.factorsOf(4)).to eq [2, 2]
expect(PrimeFactors.of(4)).to eq [2, 2]
end

it 'decomposes 32' do
expect(PrimeFactors.factorsOf(32)).to eq [2, 2, 2, 2, 2]
expect(PrimeFactors.of(32)).to eq [2, 2, 2, 2, 2]
end

it 'decomposes 25' do
expect(PrimeFactors.of(25)).to eq [5,5]
end

it 'decomposes 50' do
expect(PrimeFactors.of(50)).to eq [2,5,5]
end

end

0 comments on commit 552a382

Please sign in to comment.