Problem 23
http://projecteuler.net/index.php?section=problems&id=23
ひさしぶりに。
import Data.List (filter) import Data.IntSet (fromList, member) import Prime (divisors) main = print $ sum $ filter f [1..n] where f = not . (isTheSumOfTwoAbundantNumbers $ abundants n) n = 28123 isTheSumOfTwoAbundantNumbers abundants n = any f $ [1..(n `div` 2)] where f i = (member i abundants) && (member (n - i) abundants) abundants n = fromList $ filter isAbundant [1..n] isAbundant i = i < fromIntegral (sum $ divisors i)
module Prime (primes, primeFactors, divisors) where import Data.List (group, map, inits) primes :: Integral a => [a] primes = 2 : filter isPrime [3,5..] isPrime :: Integral a => a -> Bool isPrime q = all ((/= 0) . mod q) belowPrimes where belowPrimes = takeWhile (<= (floor . sqrt . fromIntegral) q) primes primeFactors :: Integral a => a -> [a] primeFactors n = f n primes where f 1 _ = [] f n ps@(p:ps') | n `mod` p == 0 = p : f (n `div` p) ps | otherwise = f n ps' divisors :: Integral a => a -> [a] divisors n = init $ comb $ map (map product . inits) $ group $ primeFactors n where comb [] = [1] comb (xs:xss) = [ x * y | x <- xs, y <- comb xss]
Intel Core2 Duo 2.2GHzで38秒くらい。
Data.ArrayよりData.IntSetの方が3秒速い。