Last active
August 29, 2015 14:15
-
-
Save scott-fleischman/4962e31449d6bdd3ec38 to your computer and use it in GitHub Desktop.
Unfaithful Sieve vs Naive Prime Algorithm - See "The Genuine Sieve of Eratosthenes" by Melissa E. O'Neill
This file contains hidden or 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
| module Main where | |
| primes = 2 : [x | x <- [3..], isprime x] | |
| isprime x = all (\p -> x `mod` p > 0) (factorsToTry x) | |
| where | |
| factorsToTry x = takeWhile (\p -> p*p <= x) primes | |
| main = do | |
| let ps = take 10000 primes | |
| putStrLn $ (show . length $ ps) ++ " primes." |
This file contains hidden or 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
| $ ghc -O2 Unfaithful.hs | |
| $ time ./Unfaithful | |
| 10000 primes. | |
| real 0m3.360s | |
| user 0m3.339s | |
| sys 0m0.018s | |
| $ ghc -O2 Naive.hs | |
| $ time ./Naive | |
| 10000 primes. | |
| real 0m0.058s | |
| user 0m0.053s | |
| sys 0m0.003s |
This file contains hidden or 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
| module Main where | |
| primes = sieve [2..] | |
| where sieve (p:xs) = | |
| p : sieve [x | x <- xs, x `mod` p /= 0] | |
| main = do | |
| let ps = take 10000 primes | |
| putStrLn $ (show . length $ ps) ++ " primes." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment