require "prime" def h(n) # while n > 10 # n = n.to_s.chars.map(&:to_i).inject(0,:+) # end # n while n > 10 r = 0 while n > 0 n, m = n.divmod(10) r += m end n = r end n end def f(k, n) primes = Prime.each(n).drop_while{|n| n < k} last = -1 max = 0 r = [] primes.each_with_index{|_v,i| break if i + max > primes.size v = h(_v) idx = r.index(v) r.shift(idx+1) if idx r << v max = [max, r.size].max last = i if r.size >= max } primes[last-max+1] end K = gets.to_i N = gets.to_i p f(K, N)