Skip to content

Instantly share code, notes, and snippets.

@alogic0
Created October 30, 2016 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alogic0/996907b52a9bac0dab660892b5f02d0c to your computer and use it in GitHub Desktop.
Save alogic0/996907b52a9bac0dab660892b5f02d0c to your computer and use it in GitHub Desktop.
primes numbers, effective algorithm
-- source: http://www.garrisonjensen.com/2015/05/13/haskell-programs-are-lies.html
import qualified Data.Set as PQ
primes :: [Integer]
primes = 2:sieve [3,5..]
where
sieve (x:xs) = x : sieve' xs (insertprime x xs PQ.empty)
sieve' (x:xs) table
| nextComposite == x = sieve' xs (adjust x table)
| otherwise = x : sieve' xs (insertprime x xs table)
where
(nextComposite,_) = PQ.findMin table
adjust x table
| n == x = adjust x (PQ.insert (n', ns) newPQ)
| otherwise = table
where
Just ((n, n':ns), newPQ) = PQ.minView table
insertprime p xs = PQ.insert (p*p, map (*p) xs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment