diff --git a/haskell/Util/Primes.hs b/haskell/Util/Primes.hs new file mode 100644 index 0000000..4db1078 --- /dev/null +++ b/haskell/Util/Primes.hs @@ -0,0 +1,15 @@ +module Util.Primes where + +is_prime :: (Integral a) => a -> Bool +is_prime n + | n == 1 = False + | n < 4 = True + | n `rem` 2 == 0 = False + | n < 9 = True + | n `rem` 3 == 0 = False + | otherwise = do + let f = sqrt (fromIntegral n) + let checkprime x = (n `rem` x == 0 || n `rem` (x + 2) == 0) + not (or (map checkprime (takeWhile (<= floor f) [5,11..]))) + +primes = filter is_prime (2:[3,5..]) diff --git a/haskell/e007.hs b/haskell/e007.hs index 5f3dc1a..5f42fe8 100644 --- a/haskell/e007.hs +++ b/haskell/e007.hs @@ -5,20 +5,7 @@ What is the 10001st prime number? -} import Text.Printf - -is_prime :: (Integral a) => a -> Bool -is_prime n - | n == 1 = False - | n < 4 = True - | n `rem` 2 == 0 = False - | n < 9 = True - | n `rem` 3 == 0 = False - | otherwise = do - let f = sqrt (fromIntegral n) - let checkprime x = (n `rem` x == 0 || n `rem` (x + 2) == 0) - not (or (map checkprime (takeWhile (<= floor f) [5,11..]))) - -primes = filter is_prime (2:[3,5..]) +import Util.Primes (primes) main = do printf " 6th prime: %d\n" (primes !! 5 :: Integer) diff --git a/haskell/e010.hs b/haskell/e010.hs new file mode 100644 index 0000000..d5d2d5f --- /dev/null +++ b/haskell/e010.hs @@ -0,0 +1,12 @@ +{- Calculate the sum of all the primes below two million. + +The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. +Find the sum of all the primes below two million. +-} + +import Text.Printf (printf) +import Util.Primes (primes) + +main = do + printf "Sum of primes below 10: %d\n" (sum (takeWhile (<10) primes)) + printf "Sum of primes below 2,000,000: %d\n" (sum (takeWhile (<2000000) primes))