Created
August 10, 2018 13:39
-
-
Save kidandcat/0e921baa2926ae2e2ca797af2a7b30da to your computer and use it in GitHub Desktop.
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 Control.Monad (forM_, when) | |
import Control.Monad.ST | |
import Data.Array.ST | |
import Data.Array.Unboxed | |
import System.Environment | |
sieve :: Int -> UArray Int Bool | |
sieve n = runSTUArray $ do | |
let m = (n-1) `div` 2 | |
r = floor . sqrt $ fromIntegral n | |
bits <- newArray (0, m-1) True | |
forM_ [0 .. r `div` 2 - 1] $ \i -> do | |
isPrime <- readArray bits i | |
when isPrime $ do | |
forM_ [2*i*i+6*i+3, 2*i*i+8*i+6 .. (m-1)] $ \j -> do | |
writeArray bits j False | |
return bits | |
primes :: Int -> [Int] | |
primes n = 2 : [2*i+3 | (i, True) <- assocs $ sieve n] | |
main = do | |
(arg:_) <- getArgs | |
let x = read arg | |
print $ sum $ primes x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment