Question
The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
Haskell
primes :: [Int]
= 2 : sieve primes [3,5..] where
primes :ps) xs = h ++ sieve ps [x | x <- t, rem x p /= 0]
sieve (pwhere (h, t) = span (< p*p) xs
isPrime :: Int -> Bool
| n < 1 = False
isPrime n | otherwise = not $ or [n `rem` x == 0 | x <- [2..floor $ sqrt $ fromIntegral n]]
filterPairs :: Int -> [Int] -> [Int]
= filter test where
filterPairs p = isPrime (read $ show x ++ show p) && isPrime (read $ show p ++ show x)
test x
candidates :: [[Int]]
= [[a, b, c, d, e] | a <- primes',
candidates let bs = filterPairs a $ dropWhile (<= a) primes',
<- bs,
b let cs = filterPairs b $ dropWhile (<= b) bs,
<- cs,
c let ds = filterPairs c $ dropWhile (<= c) cs,
<- ds,
d let es = filterPairs d $ dropWhile (<= d) ds,
<- es]
e where primes' = takeWhile (< 10000) primes
main :: IO ()
= print $ sum $ head candidates main
$ ghc -O2 -o prime-pairs prime-pairs.hs
$ time ./prime-pairs
real 0m0.351s
user 0m0.351s
sys 0m0.000s