Project Euler 解答

Project Euler Problem 007

Project Euler Problem 007

import Data.List hiding (union) --003より --http://www.haskell.org/haskellwiki/Prime_numbers 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 factor :: Integer -> [Integer] factor n = factorimpl n 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 solve :: Int -> Integer solve n = last \$ take n primes m :: Integer m = solve 10001 -- 104743 main :: IO () main = print m -- シンプルな別解 {- primes = 2:f [3] [3,5..] where f (x:xs) ys = ps ++ f(xs++ps) [z|z<-qs,z`rem`x/=0] where (ps,qs) = span(< x*x) ys m = primes !! (10^4) --104743 -- -}
• はじめに
• プロジェクトオイラー問題
• リンク等