Monday 6 June 2016

Haskell: Get all divisors of a number

Following statement gives all the divisors of a number.


divisors num = [x | x <- [1.. (num `div` 2)], num `rem` x == 0] ++ [num]
Prelude> let divisors num = [x | x <- [1.. (num `div` 2)], num `rem` x == 0] ++ [num]
Prelude> divisors 20
[1,2,4,5,10,20]
Prelude> 
Prelude> divisors 100
[1,2,4,5,10,20,25,50,100]
Prelude> 
Prelude> divisors 181
[1,181]
Prelude> 
Prelude> divisors 81
[1,3,9,27,81]



Previous                                                 Next                                                 Home

No comments:

Post a Comment