Problem40 in Ruby. (Could use optimization)