import scala.collection.immutable.IndexedSeq import scala.io.StdIn object Problem012 { def primesIn(max: Int): IndexedSeq[Int] = { val checked = Array.fill(max + 1)(false) for { i <- 2 to max if !checked(i) } yield { (i to max by i) foreach { checked(_) = true } i } } def proc(n: Int, a: Seq[Int]): Int = { if (n == 10) return 5000000 - 1 val primes = primesIn(5000000) val requiredChar: Set[Int] = a.map(_ + '0').toSet var result = -1 var K = 1 var usingChar: Set[Int] = Set.empty var inRange = false def outOfRange(p: Int): Boolean = inRange && !isValid(p) def isValid(p: Int): Boolean = (p.toString.map(_.toInt).toSet diff requiredChar).isEmpty primes foreach { p => if (isValid(p)) { usingChar ++= p.toString.map(_.toInt).toSet inRange = true } else if (outOfRange(p)) { if (usingChar == requiredChar) { val L = p - 1 result = result max (L - K) } usingChar = Set.empty inRange = false K = p + 1 } else if (!isValid(p)) { K = p + 1 } } result } def main(args: Array[String]) { val n = StdIn.readInt() val a = StdIn.readLine().split(" ").map(_.toInt) val result: Int = proc(n, a) println(result) } }