fork(3) download
  1. -- from http://w...content-available-to-author-only...l.org/haskellwiki/Prime_numbers#Using_ST_Array
  2.  
  3. {-# OPTIONS -O2 -optc-O3 #-}
  4. import Data.Word
  5. import Control.Monad
  6. import Control.Monad.ST
  7. import Data.Array.ST
  8. import Data.Array.Unboxed
  9. import Data.Array.Base
  10.  
  11. primesToUA :: Word32-> [Word32]
  12. primesToUA top = do
  13. let sieveUA top = runSTUArray $ do
  14. let m = ((fromIntegral top) - 3) `div` 2 :: Int
  15. buf <- newArray (0,m) True -- :: ST s (STUArray s Int Bool)
  16. let cullUA i = do
  17. let p = i + i + 3
  18. strt = p * (i + 1) + i
  19. let cull j = do
  20. if j > m then cullUA (i + 1)
  21. else do
  22. unsafeWrite buf j False
  23. cull (j + p)
  24. if strt > m then return ()
  25. else do
  26. e <- unsafeRead buf i
  27. if e then cull strt else cullUA (i + 1)
  28. cullUA 0; return buf
  29. if top > 1 then 2 : [2 * (fromIntegral i) + 3 | (i,True) <- assocs $ sieveUA top]
  30. else []
  31.  
  32. main = do
  33. x <- read `fmap` getLine -- 1mln 2mln 10mln 100mln
  34. print (length (primesToUA x)) -- 0.01 0.02 0.09 1.26 seconds
Success #stdin #stdout 1.2s 9416KB
stdin
100000000
stdout
5761455