Finding the LCM of a range of numbers

前端 未结 14 934
时光说笑
时光说笑 2020-12-08 05:03

I read an interesting DailyWTF post today, \"Out of All The Possible Answers...\" and it interested me enough to dig up the original forum post where it was submitted. This

14条回答
  •  甜味超标
    2020-12-08 06:01

    An algorithm in Haskell. This is the language I think in nowadays for algorithmic thinking. This might seem strange, complicated, and uninviting -- welcome to Haskell!

    primes :: (Integral a) => [a]
    --implementation of primes is to be left for another day.
    
    primeFactors :: (Integral a) => a -> [a]
    primeFactors n = go n primes where
        go n ps@(p : pt) =
            if q < 1 then [] else
            if r == 0 then p : go q ps else
            go n pt
            where (q, r) = quotRem n p
    
    multiFactors :: (Integral a) => a -> [(a, Int)]
    multiFactors n = [ (head xs, length xs) | xs <- group $ primeFactors $ n ]
    
    multiProduct :: (Integral a) => [(a, Int)] -> a
    multiProduct xs = product $ map (uncurry (^)) $ xs
    
    mergeFactorsPairwise [] bs = bs
    mergeFactorsPairwise as [] = as
    mergeFactorsPairwise a@((an, am) : _) b@((bn, bm) : _) =
        case compare an bn of
            LT -> (head a) : mergeFactorsPairwise (tail a) b
            GT -> (head b) : mergeFactorsPairwise a (tail b)
            EQ -> (an, max am bm) : mergeFactorsPairwise (tail a) (tail b)
    
    wideLCM :: (Integral a) => [a] -> a
    wideLCM nums = multiProduct $ foldl mergeFactorsPairwise [] $ map multiFactors $ nums
    

提交回复
热议问题