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.
#PrimeList #Enumerable def is_truncatable?(s) n=s.to_i return false if n<10 return false unless PrimeList.isPrime? n (1..(s.length-1)).all?{|l|PrimeList.isPrime?(s[0...l].to_i) and PrimeList.isPrime?(s[(s.length-l)..-1].to_i)} end def truncatable_from(s,l) return [s.to_i].to_set if l==0 and is_truncatable?(s) return Set.new if l==0 ret= (1..9).map{|i|s+i.to_s}.select{|ss|PrimeList.isPrime?(ss.to_i)}.map{|ss|truncatable_from(ss,l-1)} return Set.new unless ret.length > 0 return ret.inject{|u,v|u+v} end def p37 answers=Set.new len=0 while answers.size<11 len+=1 [2,3,5,7].each do |p| answers+=truncatable_from(p.to_s,len) end end puts answers.sum end