Created
October 30, 2016 06:54
-
-
Save alogic0/996907b52a9bac0dab660892b5f02d0c to your computer and use it in GitHub Desktop.
primes numbers, effective algorithm
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
-- 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