[Haskell-beginners] Perfect numbers

wman 666wman at gmail.com
Thu Oct 2 01:54:47 EDT 2008


factors :: Int -> [Int]
factors x = [z | z <- [1..(x `div` 2)], x `mod` z == 0]

is_perfect :: Int -> Bool
is_perfect x = sum(factors x) == x

do_perfect :: [Int] -> [Int]
do_perfect x = [z |z <- x, is_perfect z ]

main = print $ do_perfect [1..9000]
-- compile with ghc -O2, it's more than ten times faster for me
-- althought using 1..(x `div 2) instead of 1..x-1 is a bit of cheating ;-))



On Thu, Oct 2, 2008 at 6:45 AM, Matthew Williams <
Matthew_Williams at xyratex.com> wrote:

>  Hi Guys,
>
> I'm new to Haskell and I was wondering if you can help me:
>
> One of the first program's I tend to write when I'm looking at a new
> language is a program to generate a list of perfect numbers:
>
> --My First Perfect Number Generator
> factors :: Integer -> [Integer]
> factors x = [z | z <- [1..x-1], x `mod` z == 0]
>
> is_perfect :: Integer -> Bool
> is_perfect x = if sum(factors x) == x then True else False
>
> do_perfect :: [Integer] -> [Integer]
> do_perfect x = [z |z <- x, is_perfect z ]
>
> Then to run it:
> > do_perfect [1..9000]
>
> I'm using GHC to run it. My problem / question is this: It's running quite
> a lot slower than equivalent programs in erlang and python. I suspect it's
> down to the way I've written it. Any thoughts (or comments in general)
>
> Many thanks
>
> Matt
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20081002/4b56b37f/attachment-0001.htm


More information about the Beginners mailing list