More ruby-like solution to this problem?

Posted by RaouL on Stack Overflow See other posts from Stack Overflow or by RaouL
Published on 2010-06-11T16:23:41Z Indexed on 2010/06/11 16:53 UTC
Read the original article Hit count: 269

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?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about beginner