import Data.List import Control.Monad import qualified Data.Set as S primes :: [Int] primes = 2 : 3 : [x | i<-[1..], j<-[-1,1], let x = 6*i+j, isPrime x] where isPrime n = null [i | i <- takeWhile (\x -> x^2 <= n) primes, mod n i == 0] main = do getLine as <- map read . words <$> getLine putStrLn $ maybe "-1" show (rprime as) rprime :: [Int] -> Maybe Int rprime as = guard ((not.null) ds) >> maximum ds where sas = S.fromList (concatMap show as) ps = takeWhile (<= 5000000) primes sps = S.fromList ps ips = zip [0..] ps pcands = filter (S.null . flip S.difference sas . S.fromList . show . snd) ips punits = filter ((== sas) . S.fromList . concat . map show) (groupBySeq pcands) ds = map (diffs sps) punits groupBySeq :: [(Int, Int)] -> [[Int]] groupBySeq [] = [] groupBySeq xs@((i,p):ips) = g : groupBySeq (drop (length g) xs) where g = map (snd.snd) $ takeWhile (\(i,(j,_)) -> i==j) (zip [i..] xs) diffs :: S.Set Int -> [Int] -> Maybe Int diffs sps ps = do plb <- (succ <$> S.lookupLT (minimum ps) sps) `mplus` (Just 1) phb <- (pred <$> S.lookupGT (maximum ps) sps) `mplus` (Just 5000000) return (phb - plb)