fork 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 Control.Monad
  5. import Control.Monad.ST
  6. import Data.Array.ST
  7. import Data.Array.Unboxed
  8.  
  9. sieveUA :: Int -> UArray Int Bool
  10. sieveUA top = runSTUArray $ do
  11. let m = (top-1) `div` 2
  12. r = floor . sqrt $ fromIntegral top + 1
  13. sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)
  14. forM_ [1..r `div` 2] $ \i -> do
  15. isPrime <- readArray sieve i
  16. when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)
  17. forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do
  18. writeArray sieve j False
  19. return sieve
  20.  
  21. primesToUA :: Int -> [Int]
  22. primesToUA top | top > 1 = 2 : [2*p + 1 | (p,True) <- assocs $ sieveUA top]
  23. | otherwise = []
  24.  
  25. main = do
  26. x <- read `fmap` getLine -- 1mln 2mln 10mln 100mln
  27. print (last (primesToUA x)) -- 0.05 0.10 0.56 6.61 seconds
Success #stdin #stdout 6.79s 9368KB
stdin
100000000
stdout
99999989