Digital root/Multiplicative digital root: Difference between revisions

Initial Haskell version.
(→‎{{header|Python}}: Add faster implementation.)
(Initial Haskell version.)
Line 153:
}</lang>
The output is similar.
 
=={{header|Haskell}}==
Note that in the function <code>mdrNums</code> we don't know in advance how many numbers we'll need to examine to find the first 5 associated with all the MDRs. Using a lazy array to accumulate these numbers allows us to keep the function simple.
<lang haskell>import Control.Arrow
import Data.Array
import Data.LazyArray
import Data.List (unfoldr)
import Data.Tuple
import Text.Printf
 
-- The multiplicative persistence (MP) and multiplicative digital root (MDR) of
-- the argument.
mpmdr :: Integer -> (Int, Integer)
mpmdr = (length *** head) . span (> 9) . iterate (product . digits)
 
-- Pairs (mdr, ns) where mdr is a multiplicative digital root and ns are the
-- first k numbers having that root.
mdrNums :: Int -> [(Integer, [Integer])]
mdrNums k = assocs $ lArrayMap (take k) (0,9) [(snd $ mpmdr n, n) | n <- [0..]]
 
digits :: Integral t => t -> [t]
digits 0 = [0]
digits n = unfoldr step n
where step k = if k == 0 then Nothing else Just (swap $ quotRem k 10)
 
printMpMdrs :: [Integer] -> IO ()
printMpMdrs ns = do
putStrLn "Number MP MDR"
putStrLn "====== == ==="
sequence_ [printf "%6d %2d %2d\n" n p r | n <- ns, let (p,r) = mpmdr n]
 
printMdrNums:: Int -> IO ()
printMdrNums k = do
putStrLn "MDR Numbers"
putStrLn "=== ======="
let showNums = unwords . map show
sequence_ [printf "%2d %s\n" mdr $ showNums ns | (mdr,ns) <- mdrNums k]
 
main :: IO ()
main = do
printMpMdrs [123321, 7739, 893, 899998]
putStrLn ""
printMdrNums 5</lang>
{{out}}
Note that the values in the first column of the table are MDRs, as shown in the task's sample output, not MP as incorrectly stated in the task statement and column header.
<pre>Number MP MDR
====== == ===
123321 3 8
7739 3 8
893 3 2
899998 2 0
 
MDR Numbers
=== =======
0 0 10 20 25 30
1 1 11 111 1111 11111
2 2 12 21 26 34
3 3 13 31 113 131
4 4 14 22 27 39
5 5 15 35 51 53
6 6 16 23 28 32
7 7 17 71 117 171
8 8 18 24 29 36
9 9 19 33 91 119</pre>
 
=={{header|Python}}==
Anonymous user