fork(1) download
  1. -- sum of primes
  2. -- https://p...content-available-to-author-only...s.com/
  3. -- 2012/09/programmingwithprimenumbers.pdf
  4.  
  5. import Control.Monad (forM_, when)
  6. import Control.Monad.ST
  7. import Data.Array.ST
  8. import Data.Array.Unboxed
  9.  
  10. sieve :: Int -> UArray Int Bool
  11. sieve n = runSTUArray $ do
  12. let m = (n-1) `div` 2
  13. bits <- newArray (0, m-1) True
  14. forM_ [0 .. r `div` 2 - 1] $ \i -> do
  15. isPrime <- readArray bits i
  16. when isPrime $ do
  17. let a = 2*i*i + 6*i + 3
  18. b = 2*i*i + 8*i + 6
  19. forM_ [a, b .. (m-1)] $ \j -> do
  20. writeArray bits j False
  21. return bits
  22.  
  23. primes :: Int -> [Int]
  24. primes n = 2 : [2*i+3 | (i, True) <- assocs $ sieve n]
  25.  
  26. main = do
  27. print $ sum $ primes 1000000
Success #stdin #stdout 0.02s 8388607KB
stdin
Standard input is empty
stdout
37550402023