RosettaCodeData/Task/Smith-numbers/Miranda/smith-numbers.miranda
2023-07-01 13:44:08 -04:00

28 lines
951 B
Text

main :: [sys_message]
main = [Stdout (table 5 16 taskOutput),
Stdout ("Found " ++ show (#taskOutput) ++ " Smith numbers.\n")]
where taskOutput = takewhile (<= 10000) smiths
table :: num->num->[num]->[char]
table cw w ns = lay (map concat (split (map fmt ns)))
where split [] = []
split ls = take w ls : split (drop w ls)
fmt n = reverse (take cw ((reverse (shownum n)) ++ repeat ' '))
smiths :: [num]
smiths = filter smith [1..]
smith :: num->bool
smith n = (~ prime) & digsum n = sum (map digsum facs)
where facs = factors n
prime = #facs <= 1
digsum :: num->num
digsum 0 = 0
digsum n = n mod 10 + digsum (n div 10)
factors :: num->[num]
factors = f [] 2
where f acc d n = acc, if d>n
= f (d:acc) d (n div d), if n mod d = 0
= f acc (d+1) n, otherwise