What is the best way to list all divisors of a number?
A divisor of a number n
is another number d
where there is some number k
such that n = d k
In particular 1
and n
are always divisors.
module Divisors where
divisors :: Integer -> [Integer]
divisors n = 1:n:(divisorsAux 2)
where
divisorsAux k
| (fromIntegral k) > sqrt (fromIntegral n) = []
| otherwise = if n `mod` k == 0
then if n`div`k ==k
then k:(divisorsAux (k+1))
else k:(n`div`k):(divisorsAux (k+1))
else divisorsAux (k+1)
module ExampleSpec where
import Test.Hspec
import Divisors
import Data.List
-- `spec` of type `Spec` must exist
spec :: Spec
spec = do
describe "divisorList" $ do
it "divisors of 5*4*3 = 60" $ do
(sort(divisors (5*4*3))) `shouldBe` [1,2,3,4,5,6,10,12,15,20,30,60]
it "divisors of 4" $ do
(sort(divisors 4)) `shouldBe` [1,2,4]
it "divisors of 5*3 = 15" $ do
(sort(divisors (5*3))) `shouldBe` [1,3,5,15]
it "divisors of 101" $ do
(sort(divisors 101)) `shouldBe` [1,101]