How to create a special kind of list?

Viewed 83

I have to create a special kind of list in Haskell. First I had to create a function whether it's an abundant number or not. An abundant number is when summing the divisors of number the result is bigger then the double of the original number, for example in the case of

12-> 1,2,3,4,6,12 > 24

I had this solution:

 abundant n =  sum[x | x <- [1..(n-1)], n `rem` x == 0]+n> 2*n

Now I should create a list which shows you a certain number of abundant number, how should I do it?

2 Answers

I like to encourage people to think through things but there isn't much to this one.

filter abundant [1..]

This gives you an infinite list of abundant numbers. You can take from it to get a finite list.

Same answer but in the notation of list-comprehension:

[x | x <- [1..], abundant x]

Example:

take 10 ([x | x <- [1..], abundant x])

Out: [12,18,20,24,30,36,40,42,48,54]

As requested from comments, here's it all in one function:

abundantnr i = take i ([x | x <- [1..], abundant x])
                 where abundant n = sum[x | x <- [1..(n-1)], n `rem` x == 0]+n> 2*n

Usage:

abundantnr 10

Out: [12,18,20,24,30,36,40,42,48,54]

Related