소수 3797에는 왼쪽부터 자리수를 하나씩 없애거나 오른쪽부터 없애도 모두 소수가 되는 성질이 있습니다 이런 성질을 가진 소수는 단 11개만이 존재합니다. 이것을 모두 찾아서 합을 구하세요. 단, 2, 3, 5, 7 제외.


In [26]:
def find_candidates(n)
  candidates = []
  n_s = n.to_s

  (1..(n_s.length - 1)).each do |i|
    candidates << n_s[i..n_s.length].to_i
  end

  (1..(n_s.length - 1)).each do |i|
    candidates << n_s[0..n_s.length-(i+1)].to_i
  end

  return candidates
end

find_candidates(3797)


Out[26]:
[797, 97, 7, 379, 37, 3]

In [29]:
def is_prime?(num)
  return false if num == 1
  return true if num == 2
  return false if num % 2 == 0
  return (2..Math.sqrt(num).ceil).all?{|i| num % i != 0}
end

is_prime?(3797)


Out[29]:
true

In [31]:
def is_special?(n)
  find_candidates(n).all? {|n| is_prime?(n.to_i)}
end

is_special?(3797)


Out[31]:
true

In [32]:
results = []

(9..Float::INFINITY).lazy.each do |n|
  if is_prime?(n)
    results << n if is_special?(n)
  end
  break if results.length == 11
end

results


Out[32]:
[23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397]

In [33]:
results.inject &:+


Out[33]:
748317