Ad

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)