Prime factorization using list comprehension

前端 未结 1 350
無奈伤痛
無奈伤痛 2021-01-21 11:56

I want to find all prime factors of a given number using only list comprehension method and/or . (function composition operator) in Haskell. I specifically want to

相关标签:
1条回答
  • 2021-01-21 12:34

    Here's how I'd do it:

    pfactors :: Integer -> [Integer]
    pfactors n = [ p
                 | p <- [2..n]                                  -- Possible factors
                 , [d | d <- [1..p], p `mod` d == 0] == [1,p]   -- Are prime 
                 , _ <- [ p | i <- [1..n], n `mod` p^i == 0] ]  -- Divisible powers
    

    It's essentially the solution you have, but the difference is that it has an extra list comprehension at the end which contains as many elements as p factors into n.

    Disclaimer I really wouldn't do it like this in reality.

    EDIT I felt dirty writing the above, so for reference, this is something closer to what I would write:

    pfactors' :: Int -> [Int]
    pfactors' = unfoldr firstFactor
      where
        firstFactor n =
            listToMaybe [(f, n `div` f)
                        | f <- [2..n]
                        , n `mod` f == 0]
    

    Dependencies: Data.List (unfoldr), Data.Maybe (listToMaybe)

    0 讨论(0)
提交回复
热议问题