Created
April 30, 2019 03:00
-
-
Save ssadler/afa4c8dc65d034e21ca04aeed85505d9 to your computer and use it in GitHub Desktop.
Prime factors tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List (nub) | |
import Control.Monad | |
import System.Environment | |
main = getArgs >>= compressedFactors . read . head . (++["20"]) | |
-- | Reduce the number of factors needed to create a number | |
compressedFactors m = do | |
putStrLn "digraph G {" | |
putStrLn "graph [pad=\"0.5\", nodesep=\"0\", ranksep=\"2\"];" | |
mapM_ printTree [1..m::Int] | |
putStrLn "}" | |
where | |
printTree n = do | |
let facs = prime_factors n | |
forM_ (nub facs) $ \f -> do | |
putEdge n f | |
let f' = product $ tail $ filter (==f) facs | |
putEdge n f' | |
prime_factors n = | |
case factors of | |
[] -> [n] | |
_ -> factors ++ prime_factors (n `div` (head factors)) | |
where factors = take 1 $ filter (\x -> (n `mod` x) == 0) [2 .. n-1] | |
putEdge a b = | |
putStrLn $ " " ++ (show a) ++ " -> " ++ (show b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment