In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 45

After the last problem, I figure to heck with trying to optimize. Below you’ll find another brute force solution which completes in less than a second. The trick was finding the intersection of the three arrays which is a snap in Ruby. I bet the math is cool, but I completely avoided it again. Good for me, I guess.

As always, any feedback is welcome.

# Euler 45
# http://projecteuler.net/index.php?section=problems&id=45
# Triangle, pentagonal, and hexagonal numbers are
# generated by the following formulae:
#
# Triangle	 	Tn=n(n+1)/2 	1, 3, 6, 10, 15, ...
# Pentagonal	Pn=n(3n-1)/2 	1, 5, 12, 22, 35, ...
# Hexagonal	Hn=n(2n-1)	 	1, 6, 15, 28, 45, ...
# It can be verified that T285 = P165 = H143 = 40755.
#
# Find the next triangle number that is also pentagonal
# and hexagonal

timer_start = Time.now

class Integer
  def triangle
    return self * (self + 1) / 2
  end

  def pentagonal
    return self * (3 * self - 1) / 2
  end

  def hexagonal
    return self * (2 * self - 1)
  end
end

#puts 285.triangle
#puts 165.pentagonal
#puts 143.hexagonal

t, p, h = [], [], []
1.upto(100000) { |i|
  t << i.triangle
  p << i.pentagonal
  h << i.hexagonal
}

puts (t & p & h).select { |x| x > 40755}[0]
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"

One Comment to “Project Euler 45: Ruby”

Leave a Reply

You can wrap your code with [ruby][/ruby] or [python][/python] blocks for syntax highlighting and you can use these traditional tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>