import scala.io.StdIn object Problem012 { def proc(n: Int, a: Seq[Int]): Int = { val max = 5000000 if (n == 10) return max - 1 val checked = Array.fill(max + 1)(false) val requiredChar: Set[Int] = a.map(_ + '0').toSet var result = -1 var K = 1 var usingChar: Set[Int] = Set.empty var inRange = false def isValid(p: Int): Boolean = (p.toString.map(_.toInt).toSet diff requiredChar).isEmpty def outOfRange(p: Int): Boolean = inRange && !isValid(p) for { p <- 2 to max if !checked(p) } { (p to max by p).foreach(checked(_) = true) 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) } }