Skip to content

Instantly share code, notes, and snippets.

@dbfin
Created January 31, 2014 01:29
Show Gist options
  • Save dbfin/8724998 to your computer and use it in GitHub Desktop.
Save dbfin/8724998 to your computer and use it in GitHub Desktop.
-- Factor a number
factor :: Int -> [(Int, Int)]
factor n | n < 2 = []
| otherwise = factor' n (eratosthenes.floor.sqrt.fromIntegral $ n) 0 []
where
factor' :: Int -> [Int] -> Int -> [(Int, Int)] -> [(Int, Int)]
factor' n [] _ res = res ++ [(n,1)]
factor' 1 (p:ps) pw res | pw > 0 = res ++ [(p,pw)]
| otherwise = res
factor' n (p:ps) pw res | n `mod` p == 0 = factor' (n `div` p) (p:ps) (pw + 1) res
| pw > 0 = factor' n ps 0 (res ++ [(p,pw)])
| otherwise = factor' n ps 0 res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment