-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheuler049.hs
More file actions
29 lines (23 loc) · 842 Bytes
/
euler049.hs
File metadata and controls
29 lines (23 loc) · 842 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import Data.List
main = putStrLn . show $ head answer
answer :: [Integer]
answer = [ read $ (show a ++ show b ++ show c) |
a <- cs,
b <- dropWhile (<=a) cs,
sort (show a) == sort (show b),
let c = 2*b-a, -- mathematically we know that this must be true, for
-- the next permutation
prime c && sort (show a) == sort (show c)
]
cs = filter (>1487) $ primesTo 9999
primesTo :: Integer -> [Integer]
primesTo n = takeWhile ( < n) primes
primes :: [Integer]
primes = 2 : primes'
where
primes' = sieve [3,5..] 9 primes'
sieve (x:xs) q ps@ ~(p:t)
| x < q = x : sieve xs q ps
| otherwise = sieve [y | y <- xs, y `mod` p > 0] (head t^2) t
prime n =
n > 1 && foldr (\p r -> p*p > n || ((n `rem` p) /= 0 && r)) True primes