Skip to content

Instantly share code, notes, and snippets.

@jnape
Created December 23, 2012 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnape/4366618 to your computer and use it in GitHub Desktop.
Save jnape/4366618 to your computer and use it in GitHub Desktop.
Prime factorization in Haskell using unfoldr
module PrimeFactorization where
import Data.List
primeFactorsOf :: Int -> [Int]
primeFactorsOf n = (nub . unfoldr (2 `factorOutOf`)) n
where k `factorOutOf` n
| n < 2 = Nothing
| n `mod` k == 0 = Just (k, n `div` k)
| otherwise = (k+1) `factorOutOf` n
main :: IO ()
main = print $ primeFactorsOf $ foldl1 lcm [1..20] -- -> [2, 3, 5, 7, 11, 13, 17, 19]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment