Last active
September 5, 2015 05:22
-
-
Save noili/2abec3d75b97a1210020 to your computer and use it in GitHub Desktop.
prime_factors.rb
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 PrimeFactors | |
| attr_accessor :n, :primes | |
| def initialize n | |
| self.n = n | |
| self.primes = prime_divisors | |
| end | |
| def self.for n | |
| return [] if n == 1 | |
| divisors = new(n).primes | |
| prime_factors divisors, n | |
| end | |
| def self.prime_factors divisors, num | |
| return [] if num == 1 | |
| return [num] if divisors.empty? | |
| if num % divisors[0] == 0 | |
| [divisors[0]] + prime_factors(divisors, num / divisors[0]) | |
| else | |
| prime_factors(divisors[1..divisors.size], num) | |
| end | |
| end | |
| private | |
| def prime_divisors | |
| divisors = *(2..(n ** 0.5).ceil.to_i) | |
| divisors.each do |x| | |
| divisors.delete_if { |y| x != y && y % x == 0 } | |
| end | |
| divisors | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment