Product of divisors: Difference between revisions

Content added Content deleted
Line 589: Line 589:


------------------------- DIVISORS -----------------------
------------------------- DIVISORS -----------------------

divisors
:: Integral a
divisors :: Integral a => a -> [a]
=> a -> [a]
divisors n =
divisors n =
((<>) <*> (rest . reverse . fmap (quot n))) $
((<>) <*> (rest . reverse . fmap (quot n))) $
filter ((0 ==) . rem n) [1 .. root]
filter ((0 ==) . rem n) [1 .. root]
where
where
root = (floor . sqrt . fromIntegral) n
root = (floor . sqrt . fromIntegral) n
Line 602: Line 601:


-------------- SUMS AND PRODUCTS OF DIVISORS -------------
-------------- SUMS AND PRODUCTS OF DIVISORS -------------

main :: IO ()
main :: IO ()
main =
main =
mapM_
mapM_
putStrLn
putStrLn
[ "Sums of divisors of [1..100]:"
[ "Sums of divisors of [1..100]:",
, test sum
test sum,
, "Products of divisors of [1..100]:"
"Products of divisors of [1..100]:",
, test product
test product
]
]


test :: (Show a, Integral a) => ([a] -> a) -> String
test
:: (Show a, Integral a)
=> ([a] -> a) -> String
test f =
test f =
let xs = show . f . divisors <$> [1 .. 100]
let xs = show . f . divisors <$> [1 .. 100]
w = maximum $ length <$> xs
w = maximum $ length <$> xs
in unlines $
in unlines $ unwords <$> fmap (fmap (justifyRight w ' ')) (chunksOf 5 xs)
unwords
<$> fmap
(fmap (justifyRight w ' '))
(chunksOf 5 xs)


justifyRight :: Int -> Char -> String -> String
justifyRight :: Int -> Char -> String -> String