Factors of an integer: Difference between revisions

→‎{{Header|Haskell}}: upd the dead link to one via web.archive.org
(Added FutureBasic example)
(→‎{{Header|Haskell}}: upd the dead link to one via web.archive.org)
Line 1,457:
 
=={{Header|Haskell}}==
Using D. Amos module Primes [https://web.archive.org/web/20121130222921/http://www.polyomino.f2s.com/david/haskell/codeindex.html] for finding prime factors
<lang Haskell>import HFM.Primes(primePowerFactors)
import Data.List
 
-- primePowerFactors :: Integer -> [(Integer,Int)]
 
factors = map product.
Line 1,468 ⟶ 1,470:
<lang Haskell>factors_naive n = [i | i <-[1..n], (mod n i) == 0]</lang>
<lang Haskell>factors_naive 6
[1,2,3,6]</lang>
</lang>
 
Factor, cofactor. Rearrange a list of tuples to a sorted list
Line 1,478 ⟶ 1,479:
[i | i <-
[1..truncate (sqrt (fromIntegral n))]
, (mod n i) == 0]] ))</lang>
</lang>
<lang Haskell>factors_co 6
[1,2,3,6]</lang>
</lang>
 
A cleaner, simplified version of the code above, without the sorting nor the tuples, increasing speed and making it possible to see results in real time (if using GHCi)
<lang Haskell>import Data.List
factors n = lows ++ (reverse $ map (div n) lows)
where lows = filter ((== 0) . mod n) [1..truncate . sqrt $ fromIntegral n]</lang>
</lang>
<lang Haskell>*Main> :set +s
*Main> factors 120
751

edits