Skip to content

Instantly share code, notes, and snippets.

@donatello
Created August 21, 2012 10:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donatello/3414372 to your computer and use it in GitHub Desktop.
Save donatello/3414372 to your computer and use it in GitHub Desktop.
Haskell implementations to find the divisors of a number
import Data.Int (Int64)
divisors :: Int64 -> [Int64]
divisors k = divisors' 2 k
where
divisors' n k | n*n > k = [k]
| n*n == k = [n, k]
| k `mod` n == 0 = (n:(k `div` n):result)
| otherwise = result
where result = divisors' (n+1) k
divisors2 :: Int64 -> [Int64]
divisors2 k = k : (concatMap (\x -> [x, k `div` x]) $
filter (\x -> k `mod` x == 0) $
takeWhile (\x -> x*x <= k) [2..])
main = do
putStrLn.show.sum $ concatMap divisors $ [1000000..1100000]
--putStrLn.show.sum $ concatMap divisors2 $ [1000000..1100000]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment