[Haskell-cafe] Optimization fun

Bulat Ziganshin bulat.ziganshin at gmail.com
Sat Feb 10 16:19:07 EST 2007


Hello Creighton,

Sunday, February 11, 2007, 12:02:09 AM, you wrote:

> import Data.List
> primes = 2:(foldr (\x y -> if isPrime x then x:y else y) [] [3..])
>     where isPrime x = foldl' (\z y -> z && (if x `mod` y == 0 then
> False else True)) True (take (floor $ sqrt $ fromIntegral x) primes) 

my program was:

primes      = 2:filter is_prime [3,5..]
is_prime n  = all (\p-> n `mod` p /= 0) (takeWhile (\p-> p*p<=n) primes)

it's faster to calculate square instead of square root. also note that
(if x `mod` y == 0 then False else True) can be replaced with
(x `mod` y /= 0)



-- 
Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com



More information about the Haskell-Cafe mailing list