import scala.annotation.tailrec import scala.io.StdIn object Problem006 { def primesIn(min: Int, max: Int) = { val sq = Math.sqrt(max).toInt @tailrec def sieve(xs: Seq[Int], result: Seq[Int]): Seq[Int] = { if (xs.isEmpty || xs.head > sq) { (xs.reverse ++ result).reverse } else { sieve(xs.tail.filter(_ % xs.head != 0), xs.head +: result) } } sieve((2 to max).toSeq, Seq()).filter(_ >= min) } def hash(n: Int): Int = { @tailrec def rec(i: Int, result: Int): Int = { if (i == 0 && result >= 10) rec(result, 0) else if (i == 0) result else rec(i / 10, result + i % 10) } rec(n, 0) } def searchMax(primes: Seq[Int], hashes: Seq[Int]): Int = { @tailrec def rec(start: Int, end: Int, maxStart: Int, maxLen: Int): Int = { if (end > primes.length) return maxStart val range = hashes.slice(start, end) if (range.size == range.distinct.size) { if (maxLen <= end - start) { rec(start, end + 1, primes(start), end - start) } else { rec(start, end + 1, maxStart, maxLen) } } else { rec(start + 1, end, maxStart, maxLen) } } rec(0, 1, 0, 0) } def proc(min: Int, max: Int): Int = { val primes = primesIn(min, max) val hashes = primes.map(hash) searchMax(primes, hashes) } def main(args: Array[String]) = { val k = StdIn.readInt() val n = StdIn.readInt() val result = proc(k, n) println(result) } }