Project Euler: Problem 37 in Ruby

It’s been a while since I’ve done one of these, so I was afraid of being rusty but it worked out alright. I used the generator I made a while back to create the primes (pre-filled to the example given in the project) and used procs to take care of the truncation.

BAM!

Problem 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.

load 'prime_generator.rb'

def prime? n, truncate
  return false if !$primer.is_prime?(n)
  return true if n < 10
  prime? truncate.call(n), truncate
end

left = Proc.new { |n| n / 10 }
right = Proc.new { |n| n % 10**Math.log10(n).to_i }

$primer = Prime_Generator.new 3_797
n, sum, found = 0, 0, 0

while found < 11 do  
  if (n += 1) > 10 && prime?(n, left) && prime?(n, right)
    found += 1
    sum += n
  end
end

puts sum

Also, I’ve finally moved my project euler solutions over to bitbucket. Long live Mercurial!