Last active
February 8, 2020 11:02
-
-
Save noughtmare/48b5755768ddec86ad50a3908e721410 to your computer and use it in GitHub Desktop.
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 | |
import qualified Data.Vector.Unboxed.Mutable as VM | |
import qualified Data.Vector.Unboxed as V | |
import Control.Monad.ST (runST) | |
import Control.Monad (when) | |
sieve :: Int -> V.Vector Bool | |
sieve n = runST $ do | |
vm <- VM.new n | |
VM.set vm True | |
let | |
go i = when (i < n) $ do | |
x <- VM.unsafeRead vm i | |
let go' j = when (j < n) (VM.unsafeWrite vm j False *> go' (j + i)) | |
when x (go' (2 * i)) | |
go (i + 1) | |
go 2 | |
V.freeze vm | |
primes :: Int -> [Int] | |
primes = drop 2 . V.ifoldr (\i x xs -> if x then i : xs else xs) [] . sieve | |
main :: IO () | |
main = print $ primes 1000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment