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

There’s nothing pretty going on here. I can’t sleep so let’s call this a late night hack. It’s not that bad, but… Chop! — which I personally wish was called Chomp! — is new. Everything else is pretty much “meh.”

As always, any feedback is welcome.

# Euler 37
# http://projecteuler.net/index.php?section=problems&id=37
# The number 3797 has an interesting property. Being prime
# itself, it is possible to continuously remove digits from
# left to right, and remain prime at each stage:
# 3797, 797, 97, and 7. Similarly we can work from right to
# left: 3797, 379, 37, and 3.
#
# Find the sum of the only eleven primes that are both
# truncatable from left to right and right to left.
#
# NOTE: 2, 3, 5, and 7 are not considered to be
# truncatable primes.
timer_start = Time.now

require 'mathn'

def truncatable_prime?(i)
  nums = i.to_s.chars.to_a

  nums.length.times do
    return false if (!nums.join().to_i.prime?)
    nums.shift
  end

  nums = i.to_s
  while nums.length > 0
    return false if (!nums.to_i.prime?)
    nums.chop!()
  end

  return true
end

count = 0
answer = 0

Prime.each { |x|
  next if x < 10
  break if count == 11
  if truncatable_prime?(x)
    count +=1
    answer += x
  end
}

puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"

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>