Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

90% of /prog/ cannot write this BASIC PROGRAM

Name: Anonymous 2008-05-08 20:11

Task: Using your language of choice, implement a program that will a) Prompt the user for 2 numbers, and b) output the number of prime numbers between the two numbers (inclusive.)

Output: A B N

Name: Anonymous 2008-05-09 23:05

>>30
That may be beautiful and short, but it's dog slow. Here's one with a decent performance:

import System
import Data.Array.Unboxed

listUArray :: (IArray UArray e, Ix i) => (i, i) -> [e] -> UArray i e
listUArray = listArray

sieve limit = sieveLoop 1 $ listUArray (1, limit) $ False: repeat True
   where
   sqrtLimit = floor (sqrt $ fromIntegral limit)
   sieveLoop last numbers | prime <= sqrtLimit = prime: sieveLoop prime nextNums
                          | otherwise          = map fst $ filter snd $ assocs numbers
      where
      prime = fst $ head $ filter snd $ drop last $ assocs numbers
      nextNums = numbers // zip (tail [0, prime..limit]) (repeat False)

main = do [lo, hi] <- mapM readIO . words =<< getLine
          print $ length $ dropWhile (<lo) $ sieve hi

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List