Euler problem 27

primes :: [Int]
primes = 2 : filter (null . tail . primeFactors) [3,5..]

primeFactors :: Int -> [Int]
primeFactors n = factor n primes
  where
    factor n (p : ps)
      | p * p > n = [n]
      | n `mod` p == 0 = p : factor (n `div` p) (p : ps)
      | otherwise = factor n ps

listMax :: Ord a => [a] -> a
listMax (x : xs) = lmf x xs
  where
    lmf x [] = x
    lmf x xs
      | x >= head xs = lmf x (tail xs)
      | otherwise = lmf (head xs) (tail xs)

elemInd :: (Num a, Eq t) => t -> [t] -> a
elemInd y [] = -1
elemInd y (x : xs) = ei 0 y (x : xs)
  where
    ei n y (x : xs)
      | x == y = n
      | null xs = -1
      | otherwise = ei (n + 1) y xs

bList :: [Int]
bList = takeWhile (<= 1000) primes

isPrime :: Int -> Bool
isPrime x | x <= 1    = False
          | otherwise = null $ tail (primeFactors x)

cPrimeLen :: [Int] -> [Int]
cPrimeLen [a, b] = [m, a, b]
    where
      m = length $ takeWhile (isPrime . (\n -> n^2 + a*n + b)) [0..]

p27List :: [[Int]]
p27List = [cPrimeLen [a, b] | a <- [-n..n], b <- bList]
  where
    n = 1000

p27n :: [Int]
p27n = map head p27List

p27 :: [Int]
p27 = p27List !! elemInd (listMax p27n) p27n

λ> :set +s
λ> p27
[71,-61,971]
(2.97 secs, 3,146,880,176 bytes)
λ> 

— Me@2015-06-19 10:01:22 PM

— Me@2025-02-20 04:34:12 PM

.

.

2015.06.20 Saturday (c) All rights reserved by ACHK