Created
August 29, 2013 00:58
-
-
Save broguinn/6373164 to your computer and use it in GitHub Desktop.
prime_factors
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
require 'sieve' | |
def prime_factors_parent(number) | |
primes = prime_sift(number) | |
prime_factors(number, primes) | |
end | |
def prime_factors(number, primes, factors=[]) | |
if primes.include?(number) | |
factors << number | |
else | |
first_prime = primes.find { |prime| number % prime == 0 } | |
factors << first_prime | |
prime_factors(number / first_prime, primes, factors) | |
end | |
end |
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
require 'rspec' | |
require 'prime_factors' | |
describe 'prime_factors' do | |
it 'returns an array for the prime factors of any number greater than one' do | |
expect { prime_factors_parent(1) }.to raise_exception | |
end | |
it 'returns an array of prime factors up through 16' do | |
prime_factors_parent(9).should eq [3, 3] | |
prime_factors_parent(8).should eq [2, 2, 2] | |
prime_factors_parent(16).should eq [2, 2, 2, 2] | |
prime_factors_parent(625).should eq [5, 5, 5, 5] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment