Created
December 31, 2015 22:28
-
-
Save ktec/2efb3659c984f4d9f0ec to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes in Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List | |
import qualified Data.Map as Map | |
import System.Environment (getArgs) | |
-- credit The Genuine Sieve of Eratosthenes (Melissa E. O’Neill) | |
sieve xs = sieve' xs Map.empty | |
sieve' [] table = [] | |
sieve' (x:xs) table = | |
case Map.lookup x table of | |
Nothing -> x: sieve' xs (Map.insert (x*x) [x] table) | |
Just facts -> sieve' xs (foldl' reinsert (Map.delete x table) facts) | |
where reinsert table prime = Map.insertWith (++) (x+prime) [prime] table | |
primes = 2 : sieve [3,5..] | |
-- module Main (main) where | |
main :: IO () | |
main = do | |
args <- getArgs | |
let lim = case args of | |
(a:_) -> read a | |
_ -> 1000000 | |
print . sum $ takeWhile (<= lim) primes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment