Search code examples
rubyrefactoringfactorization

More ruby-like solution to this problem?


I am learning ruby and practicing it by solving problems from Project Euler.

This is my solution for problem 12.

# Project Euler problem: 12
# What is the value of the first triangle number to have over five hundred divisors?

require 'prime'

triangle_number = ->(num){ (num *(num + 1)) / 2 }

factor_count = ->(num) do
  prime_fac = Prime.prime_division(num)
  exponents = prime_fac.collect { |item| item.last + 1 }
  fac_count = exponents.inject(:*)
end

n = 2
loop do
  tn = triangle_number.(n)
  if factor_count.(tn) >= 500
    puts tn
    break
  end
  n += 1
end

Any improvements that can be made to this piece of code?


Solution

  • Rather than solve the problem in one go, looking at the individual parts of the problem might help you understand ruby a bit better.

    The first part is finding out what the triangle number would be. Since this uses sequence of natural numbers, you can represent this using a range in ruby. Here's an example:

    (1..10).to_a => [1,2,3,4,5,6,7,8,9,10]
    

    An array in ruby is considered an enumerable, and ruby provides lots of ways to enumerate over data. Using this notion you can iterate over this array using the each method and pass a block that sums the numbers.

    sum = 0
    (1..10).each do |x|
      sum += x
    end
    
    sum => 55
    

    This can also be done using another enumerable method known as inject that will pass what is returned from the previous element to the current element. Using this, you can get the sum in one line. In this example I use 1.upto(10), which will functionally work the same as (1..10).

    1.upto(10).inject(0) {|sum, x| sum + x} => 55
    

    Stepping through this, the first time this is called, sum = 0, x = 1, so (sum + x) = 1. Then it passes this to the next element and so sum = 1, x = 2, (sum + x) = 3. Next sum = 3, x = 3, (sum + x) = 6. sum = 6, x = 4, (sum + x) = 10. Etc etc.

    That's just the first step of this problem. If you want to learn the language in this way, you should approach each part of the problem and learn what is appropriate to learn for that part, rather than tackling the entire problem.

    REFACTORED SOLUTION (though not efficient at all)

    def factors(n)
      (1..n).select{|x| n % x == 0}
    end
    
    def triangle(n)
      (n * (n + 1)) / 2
    end
    
    n = 2
    
    until factors(triangle(n)).size >= 500
      puts n
      n += 1
    end
    
    puts triangle(n)