Project Euler Problem 027
import Data.Ord import Data.List hiding (union) --003より primes :: [Integer] primes = 2 : ([3,5..] `minus` join [[p*p, p*p+2*p..] | p <- primes']) where primes' = 3 : ([5,7..] `minus` join [[p*p, p*p+2*p..] | p <- primes']) join ((x:xs):t) = x : union xs (join (pairs t)) pairs ((x:xs):ys:t) = (x : union xs ys) : pairs t union (x:xs) (y:ys) = case (compare x y) of LT -> x : union xs (y:ys) EQ -> x : union xs ys GT -> y : union (x:xs) ys union xs [] = xs union [] ys = ys minus (x:xs) (y:ys) = case (compare x y) of LT -> x : minus xs (y:ys) EQ -> minus xs ys GT -> minus (x:xs) ys minus xs _ = xs --必要に応じてgroupする factor :: Integer -> [Integer] factor nn = factorimpl nn primes where factorimpl n pri@(p:xs) = if p*p>n then [n] else if n`rem` p == 0 then p:factorimpl (n `quot` p) pri else factorimpl n xs divsum :: Integer -> Integer divsum n = (product. map tohi .group . factor) n - n where tohi [x] = x+1 tohi l@(x:_) = (x^(length l+1)-1) `quot` (x-1) isprime :: Integer -> Bool isprime nn = if nn<0 then False else imp nn primes where imp n (x:xs) = if x*x>n then True else if rem n x==0 then False else imp n xs quad :: Num a => a -> a -> a -> a quad a b n = n^(2::Integer)+a*n+b consect :: Num a => Integer -> Integer -> a consect aa bb = imp aa bb 0 where imp a b n = let r = quad a b n in if isprime r then 1 + imp a b (n+1) else 0 abrange :: [Integer] abrange = [-999..999] --(71,(-61,971)) ans :: (Integer, (Integer, Integer)) ans = maximumBy (comparing fst) [(c,(a,b))|a<-abrange,b<-abrange,let c=consect a b, c>40] ansv :: Integer ansv = let r = snd ans in (fst r)*(snd r) -- -59231 main :: IO () main = print ansv