Digital root/Multiplicative digital root: Difference between revisions

Added Easylang
No edit summary
(Added Easylang)
 
(44 intermediate revisions by 23 users not shown)
Line 27:
</pre>
Show all output on this page.
 
;Similar:
The Product of decimal digits of n page was redirected here, and had the following description<br>
Find the product of the decimal digits of a positive integer &nbsp; '''n''', &nbsp; where '''n <= 100'''
The three existing entries for Phix, REXX, and Ring have been moved here, under <nowiki>===Similar===</nowiki> headings, feel free to match or ignore them.
 
 
Line 32 ⟶ 37:
* [http://mathworld.wolfram.com/MultiplicativeDigitalRoot.html Multiplicative Digital Root] on Wolfram Mathworld.
* [http://oeis.org/A031347 Multiplicative digital root] on The On-Line Encyclopedia of Integer Sequences.
* [https://www.youtube.com/watch?v=Wim9WJeDTHQ What's special about 277777788888899?] - Numberphile video
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F mdroot(n)
V count = 0
V mdr = n
L mdr > 9
V m = mdr
V digits_mul = 1
L m != 0
digits_mul *= m % 10
m = m I/ 10
mdr = digits_mul
count++
R (count, mdr)
 
print(‘Number: (MP, MDR)’)
print(‘====== =========’)
L(n) (123321, 7739, 893, 899998)
print(‘#6: ’.format(n), end' ‘’)
print(mdroot(n))
 
[[Int]] table
table.resize(10)
V n = 0
L min(table.map(row -> row.len)) < 5
table[mdroot(n)[1]].append(n)
n++
 
print(‘’)
print(‘MP: [n0..n4]’)
print(‘== ========’)
L(val) table
print(‘#2: ’.format(L.index), end' ‘’)
print(val[0.<5])</syntaxhighlight>
 
{{out}}
<pre>
Number: (MP, MDR)
====== =========
123321: (3, 8)
7739: (3, 8)
893: (3, 2)
899998: (2, 0)
 
MP: [n0..n4]
== ========
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|Ada}}==
Line 38 ⟶ 102:
The solution uses the Package "Generic_Root" from the additive digital roots [[http://rosettacode.org/wiki/Digital_root#Ada]].
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Generic_Root; use Generic_Root;
 
procedure Multiplicative_Root is
Line 84 ⟶ 148:
TIO.New_Line;
end loop;
end Multiplicative_Root;</langsyntaxhighlight>
 
{{out}}
Line 108 ⟶ 172:
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">BEGIN # Multiplicative Digital Roots #
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
# structure to hold the results of calculating the digital root & persistence #
<lang algol68># Multiplicative Digital Roots #
MODE DR = STRUCT( INT root, INT persistence );
 
# returns the product of the digits of number #
# structure to hold the results of calculating the digital root & persistence #
OP DIGITPRODUCT = ( INT number )INT:
MODE DR = STRUCT( INT root, INT persistence );
BEGIN
 
INT result := 1;
# calculate the multiplicative digital root and persistence of a number #
PROC md root = ( INT number )DR rest := number;
WHILE result TIMESAB ( rest MOD 10 );
BEGIN
rest OVERAB 10;
 
# calculate the product of the digits of a number rest > #0
PROC digit product = ( INT number )INT: DO SKIP OD;
BEGIN result
END; # DIGITPRODUCT #
 
# calculates the multiplicative digital root and persistence of number #
INT result := 1;
OP MDROOT = ( INT number rest )DR:= number;
BEGIN
 
WHILE INT mp := 0;
resultINT TIMESABmdr (:= restABS MOD 10 )number;
restWHILE mdr > OVERAB9 10;DO
rest > 0 mp +:= 1;
DO mdr := DIGITPRODUCT mdr
SKIP OD;
OD; ( mdr, mp )
END; # MDROOT #
 
# prints a number and its MDR and MP #
result
PROC print md root = ( INT number )VOID:
END; # digit product #
BEGIN
 
INT mp : DR mdr = 0MDROOT( number );
print( ( whole( number, -6 ), ": MDR: ", whole( root OF mdr, 0 ), ", MP: ", whole( persistence OF mdr, -2 ), newline ) )
INT mdr := ABS number;
END; # print md root #
 
# prints the first few numbers with each possible Multiplicative Digital #
WHILE mdr > 9
# Root. The number of values to print is specified as a parameter #
DO
PROC tabulate mdr = ( INT number of values )VOID:
mp +:= 1;
mdr := digit product( mdr )BEGIN
[ 0 : 9, 1 : number of values ]INT mdr values;
OD;
[ 0 : 9 ]INT mdr counts;
 
mdr counts[ AT 1 ] := ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
( mdr, mp )
# find the first few numbers with each possible mdr #
END; # md root #
INT values found := 0;
 
INT required values := 10 * number of values;
# prints a number and its MDR and MP #
FOR value FROM 0 WHILE values found < required values DO
PROC print md root = ( INT number )VOID:
DR mdr = MDROOT value;
BEGIN
DR mdr = md IF mdr counts[ root( OF mdr ] < number );of values THEN
# need more values with this multiplicative digital root #
print( ( whole( number, -6 )
, ": MDR: ", whole( root values found OF mdr, 0 ) +:= 1;
, ", MP: ", whole( persistence mdr counts[ root OF mdr, -2] +:= )1;
mdr values[ root OF mdr, mdr counts[ root OF mdr ] ] := value
, newline
) FI
) OD;
END; # print mdthe rootvalues #
print( ( "MDR: [n0..n" + whole( number of values - 1, 0 ) + "]", newline ) );
 
print( ( "=== ========", newline ) );
# prints the first few numbers with each possible Multiplicative Digital #
# Root. The number of values to print is specified as a parameterFOR mdr pos FROM 1 LWB mdr values TO 1 UPB mdr values #DO
STRING separator := ": [";
PROC tabulate mdr = ( INT number of values )VOID:
print( ( whole( mdr pos, -3 ) ) );
BEGIN
FOR val pos FROM 2 LWB mdr values TO 2 UPB mdr values DO
 
[ 0 : 9, 1 : number of values ]INT print( ( separator + whole( mdr values[ mdr pos, val pos ], 0 ) ) );
[ 0 : 9 separator := ", ]INT mdr counts;"
mdr counts[ AT 1 ] := ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 )OD;
print( ( "]", newline ) )
 
OD
# find the first few numbers with each possible mdr #
END; # tabulate mdr #
 
INT# valuestask foundtest cases := 0;#
INT required values := 10 * number of values;
 
FOR value FROM 0 WHILE values found < required values
DO
DR mdr = md root( value );
IF mdr counts[ root OF mdr ] < number of values
THEN
# need more values with this multiplicative digital root #
values found +:= 1;
mdr counts[ root OF mdr ] +:= 1;
mdr values[ root OF mdr, mdr counts[ root OF mdr ] ] := value
FI
OD;
 
# print the values #
 
print( ( "MDR: [n0..n" + whole( number of values - 1, 0 ) + "]", newline ) );
print( ( "=== ========", newline ) );
FOR mdr pos FROM 1 LWB mdr values TO 1 UPB mdr values
DO
STRING separator := ": [";
print( ( whole( mdr pos, -3 ) ) );
FOR val pos FROM 2 LWB mdr values TO 2 UPB mdr values
DO
print( ( separator + whole( mdr values[ mdr pos, val pos ], 0 ) ) );
separator := ", "
OD;
print( ( "]", newline ) )
OD
 
END; # tabulate mdr #
 
main:(
print md root( 123321 );
print md root( 7739 );
Line 210 ⟶ 241:
print md root( 899998 );
tabulate mdr( 5 )
END</syntaxhighlight>
)</lang>
{{out}}
<pre>
Line 232 ⟶ 263:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% calculate the Multiplicative Digital Root (mdr) and Multiplicative Persistence (mp) of n %
procedure getMDR ( integer value n
Line 297 ⟶ 328:
end
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 320 ⟶ 351:
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk"># Multiplicative Digital Roots
 
BEGIN {
Line 395 ⟶ 426:
} # for pos
 
} # tabulateMdr</langsyntaxhighlight>
{{out}}
<pre>
Line 417 ⟶ 448:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">(
& ( MP/MDR
= prod L n
Line 462 ⟶ 493:
& put$\n
)
);</langsyntaxhighlight>
{{out}}
<pre>123321 : (3.8)
Line 480 ⟶ 511:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
 
Line 539 ⟶ 570:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 562 ⟶ 593:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 600 ⟶ 631:
Console.WriteLine(" {0} : [{1}]", i, string.Join(", ", table[i]));
}
}</langsyntaxhighlight>
{{out}}
<pre>123321 has multiplicative persistence 3 and multiplicative digital root 8
Line 618 ⟶ 649:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iomanip>
#include <map>
Line 678 ⟶ 709:
return system( "pause" );
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 703 ⟶ 734:
+-------+------------------------------------+
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">digits = iter (n: int) yields (int)
while n>0 do
yield(n//10)
n := n/10
end
end digits
 
mdr = proc (n: int) returns (int,int)
i: int := 0
while n>=10 do
m: int := 1
for d: int in digits(n) do
m := m * d
end
n := m
i := i+1
end
return (i,n)
end mdr
 
first_mdr = iter (target_mdr, n: int) yields (int)
i: int := 0
while n>0 do
x, m: int := mdr(i)
if m=target_mdr then
yield(i)
n := n -1
end
i := i+1
end
end first_mdr
 
start_up = proc ()
po: stream := stream$primary_output()
nums: sequence[int] := sequence[int]$[123321, 7739, 893, 899998]
stream$putl(po, " N MDR MP")
stream$putl(po, "====== === ==")
for num: int in sequence[int]$elements(nums) do
stream$putright(po, int$unparse(num), 6)
stream$puts(po, " ")
i, m: int := mdr(num)
stream$putright(po, int$unparse(m), 3)
stream$puts(po, " ")
stream$putright(po, int$unparse(i), 3)
stream$putl(po, "")
end
stream$putl(po, "\nMDR: [n0..n4]")
stream$putl(po, "=== ========")
for dgt: int in int$from_to(0,9) do
stream$putright(po, int$unparse(dgt), 3)
stream$puts(po, ": ")
for num: int in first_mdr(dgt, 5) do
stream$puts(po, int$unparse(num) || " ")
end
stream$putl(po, "")
end
end start_up</syntaxhighlight>
{{out}}
<pre> N MDR MP
====== === ==
123321 8 3
7739 8 3
893 2 3
899998 0 2
 
MDR: [n0..n4]
=== ========
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|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun mdr/p (n)
"Return a list with MDR and MP of n"
Line 730 ⟶ 842:
do (format t "~6@a: ~{~3@a ~}~%" el (mdr/p el)))
(format t "~%MDR: [n0..n4]~%")
(first-n-number-for-each-root 5))</langsyntaxhighlight>
{{out}}
<pre>
Line 753 ⟶ 865:
=={{header|Component Pascal}}==
{{Works with| BlackBox Component Builder}}
<langsyntaxhighlight lang="oberon2">
MODULE MDR;
IMPORT StdLog, Strings, TextMappers, DevCommanders;
Line 823 ⟶ 935:
 
END MDR.
</syntaxhighlight>
</lang>
Execute:
^Q MDR.Do 123321 7739 893 899998 ~
Line 848 ⟶ 960:
9: 9 19 33 91 119
</pre>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.range, std.conv;
 
/// Multiplicative digital root.
Line 876 ⟶ 989:
foreach (const mp; table.byKey.array.sort())
writefln("%2d: %s", mp, table[mp].take(5));
}</langsyntaxhighlight>
{{out}}
<pre>Number: (MP, MDR)
Line 899 ⟶ 1,012:
 
===Alternative Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.range;
 
uint digitsProduct(uint n) pure nothrow @nogc {
Line 932 ⟶ 1,045:
foreach (const mp; table.byKey.array.sort())
writefln("%2d: %s", mp, table[mp].take(5));
}</langsyntaxhighlight>
 
===More Efficient Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
/// Multiplicative digital root.
Line 970 ⟶ 1,083:
foreach (const mp; table.byKey.array.sort())
writefln("%2d: %s", mp, table[mp].take(5));
}</langsyntaxhighlight>
The output is similar.
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
proc _mdr n . md mp .
if n > 0
r = 1
.
while n > 0
r *= n mod 10
n = n div 10
.
mp += 1
if r >= 10
_mdr r md mp
else
md = r
.
.
proc mdr n . md mp .
mp = 0
_mdr n md mp
.
numfmt 0 6
print "Number MDR MP"
for v in [ 123321 7739 893 899998 ]
mdr v md mp
print v & md & mp
.
width = 5
len table[] 10 * width
arrbase table[] 0
len tfill[] 10
arrbase tfill[] 0
numfmt 0 0
while total < 10 * width
mdr i md mp
if tfill[md] < width
table[md * width + tfill[md]] = i
tfill[md] += 1
total += 1
.
i += 1
.
print "\nMDR: [n0..n4]"
for i = 0 to 9
write i & ": ["
for j = 0 to width - 1
write table[i * width + j]
if j < width - 1
write ","
.
.
print "]"
.
</syntaxhighlight>
{{out}}
<pre>
Number MDR MP
123321 8 3
7739 8 3
893 2 3
899998 0 2
 
MDR: [n0..n4]
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|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Digital do
def mdroot(n), do: mdroot(n, 0)
Line 1,010 ⟶ 1,199:
 
Digital.task1([123321, 7739, 893, 899998])
Digital.task2</langsyntaxhighlight>
 
{{out}}
Line 1,033 ⟶ 1,222:
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
</pre>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// mdr. Nigel Galloway: June 29th., 2021
let rec fG n g=if n=0 then g else fG(n/10)(g*(n%10))
let mdr n=let rec mdr n g=if n<10 then (n,g) else mdr(fG n 1)(g+1) in mdr n 0
[123321; 7739; 893; 899998] |> List.iter(fun i->let n,g=mdr i in printfn "%d has mdr=%d with persitance %d" i n g)
let fN g=Seq.initInfinite id|>Seq.filter((mdr>>fst>>(=)g))|>Seq.take 5
seq{0..9}|>Seq.iter(fun n->printf "First 5 numbers with mdr %d -> " n; Seq.initInfinite id|>Seq.filter((mdr>>fst>>(=)n))|>Seq.take 5|>Seq.iter(printf "%d ");printfn "")
</syntaxhighlight>
{{out}}
<pre>
123321 has mdr=8 with persitance 3
7739 has mdr=8 with persitance 3
893 has mdr=2 with persitance 3
899998 has mdr=0 with persitance 2
First 5 numbers with mdr 0 -> 0 10 20 25 30
First 5 numbers with mdr 1 -> 1 11 111 1111 11111
First 5 numbers with mdr 2 -> 2 12 21 26 34
First 5 numbers with mdr 3 -> 3 13 31 113 131
First 5 numbers with mdr 4 -> 4 14 22 27 39
First 5 numbers with mdr 5 -> 5 15 35 51 53
First 5 numbers with mdr 6 -> 6 16 23 28 32
First 5 numbers with mdr 7 -> 7 17 71 117 171
First 5 numbers with mdr 8 -> 8 18 24 29 36
First 5 numbers with mdr 9 -> 9 19 33 91 119
</pre>
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: arrays formatting fry io kernel lists lists.lazy math
math.text.utils prettyprint sequences ;
IN: rosetta-code.multiplicative-digital-root
 
: mdr ( n -- {persistence,root} )
0 swap
[ 1 digit-groups dup length 1 > ] [ product [ 1 + ] dip ] while
dup empty? [ drop { 0 } ] when first 2array ;
 
: print-mdr ( n -- )
dup [ 1array ] dip mdr append
"%-12d has multiplicative persistence %d and MDR %d.\n"
vprintf ;
 
: first5 ( n -- seq ) ! first 5 numbers with MDR of n
0 lfrom swap '[ mdr second _ = ] lfilter 5 swap ltake list>array ;
 
: print-first5 ( i n -- )
"%-5d" printf bl first5 [ "%-5d " printf ] each nl ;
 
: header ( -- )
"MDR | First five numbers with that MDR" print
"--------------------------------------" print ;
 
: first5-table ( -- )
header 10 iota [ print-first5 ] each-index ;
 
: main ( -- )
{ 123321 7739 893 899998 } [ print-mdr ] each nl first5-table ;
 
MAIN: main</syntaxhighlight>
{{out}}
<pre>
123321 has multiplicative persistence 3 and MDR 8.
7739 has multiplicative persistence 3 and MDR 8.
893 has multiplicative persistence 3 and MDR 2.
899998 has multiplicative persistence 2 and MDR 0.
 
MDR | First five numbers with that MDR
--------------------------------------
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|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>
!Implemented by Anant Dixit (Oct, 2014)
program mdr
Line 1,128 ⟶ 1,396:
end subroutine
 
</syntaxhighlight>
</lang>
 
<pre>
Line 1,155 ⟶ 1,423:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function multDigitalRoot(n As UInteger, ByRef mp As Integer, base_ As Integer = 10) As Integer
Line 1,206 ⟶ 1,474:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,235 ⟶ 1,503:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,289 ⟶ 1,557:
fmt.Printf(tableFmt, i, l)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,316 ⟶ 1,584:
=={{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.
<langsyntaxhighlight lang="haskell">import Control.Arrow
import Data.Array
import Data.LazyArray
Line 1,356 ⟶ 1,624:
printMpMdrs [123321, 7739, 893, 899998]
putStrLn ""
printMdrNums 5</langsyntaxhighlight>
{{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.
Line 1,382 ⟶ 1,650:
 
Works in both languages:
<langsyntaxhighlight lang="unicon">procedure main(A)
write(right("n",8)," ",right("MP",8),right("MDR",5))
every r := mdr(n := 123321|7739|893|899998) do
Line 1,405 ⟶ 1,673:
while m > 0 do c *:= 1(m%10, m/:=10)
return c
end</langsyntaxhighlight>
 
{{out}}
Line 1,434 ⟶ 1,702:
First, we need something to split a number into digits:
 
<langsyntaxhighlight Jlang="j"> 10&#.inv 123321
1 2 3 3 2 1</langsyntaxhighlight>
 
Second, we need to find their product:
 
<langsyntaxhighlight Jlang="j"> */@(10&#.inv) 123321
36</langsyntaxhighlight>
 
Then we use this inductively until it converges:
 
<langsyntaxhighlight Jlang="j"> */@(10&#.inv)^:a: 123321
123321 36 18 8</langsyntaxhighlight>
 
MP is one less than the length of this list, and MDR is the last element of this list:
 
<langsyntaxhighlight Jlang="j"> (<:@#,{:) */@(10&#.inv)^:a: 123321
3 8
(<:@#,{:) */@(10&#.inv)^:a: 7739
Line 1,456 ⟶ 1,724:
3 2
(<:@#,{:) */@(10&#.inv)^:a: 899998
2 0</langsyntaxhighlight>
 
For the table, we don't need that whole list, we only need the final value. Then use these values to classify the original argument (taking the first five from each group):
 
<langsyntaxhighlight Jlang="j"> (5&{./.~ (*/@(10&#.inv)^:_)"0) i.20000
0 10 20 25 30
1 11 111 1111 11111
Line 1,470 ⟶ 1,738:
7 17 71 117 171
8 18 24 29 36
9 19 33 91 119</langsyntaxhighlight>
 
Note that since the first 10 non-negative integers are single digit values, the first column here doubles as a label (representing the corresponding multiplicative digital root).
Line 1,476 ⟶ 1,744:
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.*;
 
public class MultiplicativeDigitalRoot {
Line 1,526 ⟶ 1,794:
return new long[]{n, mdr, mp};
}
}</langsyntaxhighlight>
 
<pre>NUMBER MDR MP
Line 1,547 ⟶ 1,815:
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def do_until(condition; next):
def u: if condition then . else (next|u) end;
u;
Line 1,578 ⟶ 1,846:
end;
 
[[], 0] | tab;</langsyntaxhighlight>
'''Example''':<langsyntaxhighlight lang="jq">
def neatly:
. as $in
Line 1,594 ⟶ 1,862:
"Tabulation",
"MDR: [n0..n4]",
(tabulate(5) | neatly)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -r -c -f mdr.jq
 
i : [MDR, MP]
Line 1,615 ⟶ 1,883:
7: [7,17,71,117,171]
8: [8,18,24,29,36]
9: [9,19,33,91,119]</langsyntaxhighlight>
 
=={{header|Julia}}==
'''Function'''
<syntaxhighlight lang="julia">
<lang Julia>
function digitalmultroot{S<:Integer,T<:Integer}(n::S, bs::T=10)
-1 < n && 1 < bs || throw(DomainError())
Line 1,630 ⟶ 1,898:
return (pers, ds)
end
</syntaxhighlight>
</lang>
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
const bs = 10
const excnt = 5
Line 1,667 ⟶ 1,935:
println(join([@sprintf("%6d", dmr[i, j]) for j in 1:excnt], ","))
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,693 ⟶ 1,961:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun multDigitalRoot(n: Int): Pair<Int, Int> = when {
Line 1,743 ⟶ 2,011:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,765 ⟶ 2,033:
9: 9 19 33 91 119
</pre>
=={{header|M2000 Interpreter}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="m2000 interpreter">multDigitalRoot=lambda (n as decimal) ->{
if n<0 then error "Negative numbers not allowed"
def decimal mdr, mp, nn
nn=n
do
mdr=IF(nn>0->1@, 0@)
while nn>0
mdr*=nn mod 10@
nn|div 10@
end while
mp++
nn=mdr
when mdr>=10
=(mdr, mp)
}
Document doc$
ia=(123321, 7739, 893, 899998)
in_ia=each(ia)
while in_ia
(mdr, mp)=multDigitalRoot(array(in_ia))
doc$=format$("{0::-9} mdr = {1} MP = {2}", array(in_ia), mdr, mp)+{
}
end while
let n=0@, count=0&
dim ia2(0 to 9, 0 to 5)
do
mdr=multDigitalRoot(n)#val(0)
if ia2(mdr, 0)<5 then
ia2(mdr, 0)++
ia2(mdr, ia2(mdr, 0))=n
count++
end if
n++
when count<50
 
doc$={MDR n0 n1 n2 n3 n4
}
doc$={=== ============================
}
for i=0 to 9
doc$=format$("{0}: ", i)
for j=1 to 5
doc$=format$("{0::-6}", ia2(i, j))
next
doc$={
}
next
Clipboard doc$
// Print like in a file (-2 is for console):
Print #-2, doc$
 
</syntaxhighlight>
{{out}}
<pre> 123321 mdr = 8 MP = 3
7739 mdr = 8 MP = 3
893 mdr = 2 MP = 3
899998 mdr = 0 MP = 2
MDR n0 n1 n2 n3 n4
=== ============================
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|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">
ClearAll[mdr, mp, nums];
mdr[n_] := NestWhile[Times @@ IntegerDigits[#] &, n, # > 9 &];
Line 1,777 ⟶ 2,116:
TableForm[Table[{i, Take[nums[[i + 1]], 5]}, {i, 0, 9}],
TableHeadings -> {None, {"MDR", "First 5"}}, TableDepth -> 2]
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,804 ⟶ 2,143:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils, futuresequtils, sugar
 
templateproc newSeqWithmdroot(lenn: int): tuple[mp, initmdr: expr): exprint] =
var result {.gensym.} = newSeq[type(init)](len)
for i in 0 .. <len:
result[i] = init
result
 
proc mdroot(n): tuple[mp, mdr: int] =
var mdr = @[n]
while mdr[mdr.high] > 9:
Line 1,820 ⟶ 2,153:
mdr.add n
(mdr.high, mdr[mdr.high])
 
for n in [123321, 7739, 893, 899998]:
echo align($n, 6)," ",mdroot(n)
echo ""
 
var table = newSeqWith(10, newSeq[int]())
for n in 0..int.high:
if table.map((x: seq[int]) => x.len).min >= 5: break
table[mdroot(n).mdr].add n
 
for mp, val in table:
echo mp, ": ", val[0..4]</langsyntaxhighlight>
 
{{out}}
<pre>123321 (mp: 3, mdr: 8)
Line 1,850 ⟶ 2,184:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">a(n)=my(i);while(n>9,n=factorback(digits(n));i++);[i,n];
apply(a, [123321, 7739, 893, 899998])
v=vector(10,i,[]); forstep(n=0,oo,1, t=a(n)[2]+1; if(#v[t]<5,v[t]=concat(v[t],n); if(vecmin(apply(length,v))>4, return(v))))</langsyntaxhighlight>
{{out}}
<pre>%1 = [[3, 8], [3, 8], [3, 2], [2, 0]]
%2 = [[0, 10, 20, 25, 30], [1, 11, 111, 1111, 11111], [2, 12, 21, 26, 34], [3, 13, 31, 113, 131], [4, 14, 22, 27, 39], [5, 15, 35, 51, 53], [6, 16, 23, 28, 32], [7, 17, 71, 117, 171], [8, 18, 24, 29, 36], [9, 19, 33, 91, 119]]</pre>
=={{header|Pascal}}==
==={{header|Free Pascal}}===
inspired by [[Worthwhile_task_shaving]] :-)<BR>
Brute force speed up GetMulDigits.
<syntaxhighlight lang="pascal">program MultRoot;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}
{$ENDIF}
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils;
type
tMul3Dgt = array[0..999] of Uint32;
tMulRoot = record
mrNum,
mrMul,
mrPers : Uint64;
end;
const
Testnumbers : array[0..16] of Uint64 =(123321,7739,893,899998,
18446743999999999999,
//first occurence of persistence 0..11
0,10,25,39,77,679, 6788, 68889, 2677889,
26888999, 3778888999, 277777788888899);
 
var
Mul3Dgt : tMul3Dgt;
 
procedure InitMulDgt;
var
i,j,k,l : Int32;
begin
l := 999;
For i := 9 downto 0 do
For j := 9 downto 0 do
For k := 9 downto 0 do
Begin
Mul3Dgt[l] := i*j*k;
dec(l);
end;
end;
 
function GetMulDigits(n:Uint64):UInt64;inline;
var
pMul3Dgt :^tMul3Dgt;
q :Uint64;
begin
pMul3Dgt := @Mul3Dgt[0];
result := 1;
while n >= 1000 do
begin
q := n div 1000;
result *= pMul3Dgt^[n-1000*q];
n := q;
end;
If n>=100 then
result *= pMul3Dgt^[n]
else
if n>=10 then
result *= pMul3Dgt^[n+100]
else
result *= n;//Mul3Dgt[n+110]
end;
 
procedure GetMulRoot(var MulRoot:tMulRoot);
var
mr,
pers : UInt64;
Begin
pers := 0;
mr := MulRoot.mrNum;
while mr >=10 do
Begin
mr := GetMulDigits(mr);
inc(pers);
end;
MulRoot.mrMul:= mr;
MulRoot.mrPers:= pers;
end;
 
const
MaxDgtCount = 9;
var
//all initiated with 0
MulRoot:tMulRoot;
Sol : array[0..9,0..MaxDgtCount-1] of tMulRoot;
SolIds : array[0..9] of Int32;
i,idx,mr,AlreadyDone : Int32;
 
BEGIN
InitMulDgt;
 
AlreadyDone := 10;//0..9
MulRoot.mrNum := 0;
repeat
GetMulRoot(MulRoot);
mr := MulRoot.mrMul;
idx := SolIds[mr];
If idx<MaxDgtCount then
begin
Sol[mr,idx]:= MulRoot;
inc(idx);
SolIds[mr]:= idx;
if idx =MaxDgtCount then
dec(AlreadyDone);
end;
inc(MulRoot.mrNum);
until AlreadyDone = 0;
writeln('MDR: First');
For i := 0 to 9 do
begin
write(i:3,':');
For idx := 0 to MaxDgtCount-1 do
write(Sol[i,idx].mrNum:MaxDgtCount+1);
writeln;
end;
writeln;
writeln('number':20,' mulroot persitance');
For i := 0 to High(Testnumbers) do
begin
MulRoot.mrNum := Testnumbers[i];
GetMulRoot(MulRoot);
With MulRoot do
writeln(mrNum:20,mrMul:8,mrPers:8);
end;
{$IFDEF WINDOWS}
readln;
{$ENDIF}
END.</syntaxhighlight>
{{out|@TIO.RUN}}
<pre>
Real time: 1.580 s CPU share: 99.59 % inline GetMulDigits ->runtime 100%->76%
MDR: First
0: 0 10 20 25 30 40 45 50 52
1: 1 11 111 1111 11111 111111 1111111 11111111 111111111
2: 2 12 21 26 34 37 43 62 73
3: 3 13 31 113 131 311 1113 1131 1311
4: 4 14 22 27 39 41 72 89 93
5: 5 15 35 51 53 57 75 115 135
6: 6 16 23 28 32 44 47 48 61
7: 7 17 71 117 171 711 1117 1171 1711
8: 8 18 24 29 36 38 42 46 49
9: 9 19 33 91 119 133 191 313 331
 
number mulroot persistence
123321 8 3
7739 8 3
893 2 3
899998 0 2
18446743999999999999 0 2
0 0 0
10 0 1
25 0 2
39 4 3
77 8 4
679 6 5
6788 0 6
68889 0 7
2677889 0 8
26888999 0 9
3778888999 0 10
277777788888899 0 11</pre>
 
=={{header|Perl}}==
{{trans|D}}
<langsyntaxhighlight Perllang="perl">use warnings;
use strict;
 
Line 1,886 ⟶ 2,384:
my @n = map { $i++ while (mdr($i))[1] != $target; $i++; } 1..5;
print " $target: [", join(", ", @n), "]\n";
}</langsyntaxhighlight>
{{out}}
<pre>Number: (MP, MDR)
Line 1,908 ⟶ 2,406:
9: [9, 19, 33, 91, 119]</pre>
 
=={{header|Perl 6}}==
<lang perl6>sub multiplicative-digital-root(Int $n) {
return .elems - 1, .[.end]
given cache($n, {[*] .comb} ... *.chars == 1)
}
 
=={{header|PicoLisp}}==
for 123321, 7739, 893, 899998 {
<syntaxhighlight lang="picolisp">(de mdr-mp (N)
say "$_: ", .&multiplicative-digital-root;
"Returns the solutions in a list, i.e., '(MDR MP)"
}
(let MP 0
(while (< 1 (length N))
(setq N (apply * (mapcar format (chop N))))
(inc 'MP) )
(list N MP) ) )
 
 
 
# Get the MDR/MP of these nums.
(setq Test-nums '(123321 7739 893 899998))
 
(let Fmt (6 5 5)
(tab Fmt "Values" "MDR" "MP")
(tab Fmt "======" "===" "==")
(for I Test-nums
(let MDR-MP (mdr-mp I)
(tab Fmt I (car MDR-MP) (cadr MDR-MP)) ) ) )
 
(prinl)
 
# Get the nums of these MDRs.
(setq *Want 5)
 
(setq *Solutions (make (for MDR (range 0 9)
(link (make (let N 0 (until (= *Want (length (made)))
(when (= MDR (car (mdr-mp N)))
(link N) )
(inc 'N) )))) )))
 
(let Fmt (3 1 -1)
(tab Fmt "MDR" ": " "Values")
(tab Fmt "===" " " "======")
(for (I . S) *Solutions
(tab Fmt (dec I) ": " (glue ", " S)) ) )</syntaxhighlight>
 
for ^10 -> $d {
say "$d : ", .[^5]
given (1..*).grep: *.&multiplicative-digital-root[1] == $d;
}</lang>
{{out}}
<pre>123321:Values 3 8MDR MP
====== === ==
7739: 3 8
123321 8 3
893: 3 2
7739 8 3
899998: 2 0
0 : 10 20893 25 30 40 2 3
1899998 : 1 11 1110 1111 11111 2
 
2 : 2 12 21 26 34
MDR: Values
3 : 3 13 31 113 131
=== ======
4 : 4 14 22 27 39
5 0: 5 150, 10, 3520, 5125, 5330
6 1: 6 161, 11, 23111, 281111, 3211111
7 2: 7 172, 12, 7121, 11726, 17134
8 3: 8 183, 13, 2431, 29113, 36131
9 4: 9 194, 14, 3322, 9127, 119</pre>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|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">mdr_mp</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">mp</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">></span><span style="color: #000000;">9</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">newm</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">m</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">newm</span> <span style="color: #0000FF;">*=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">newm</span>
<span style="color: #000000;">mp</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mp</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">123321</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7739</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">893</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">899998</span><span style="color: #0000FF;">}</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Number MDR MP\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"====== === ==\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ti</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%6d %6d %6d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">&</span><span style="color: #000000;">mdr_mp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)})</span>
<span style="color: #000080;font-style:italic;">-- (ie {{0},{1},..,{9}})</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">found</span><span style="color: #0000FF;"><</span><span style="color: #000000;">50</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- (ie the full 10*5)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">mdr1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mdr_mp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">1</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">m1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">mdr1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m1</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">6</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">mdr1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- (avoid p2js violation)</span>
<span style="color: #000000;">m1</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</span>
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">mdr1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">m1</span>
<span style="color: #000000;">found</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nMDR 1 2 3 4 5"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n=== ===========================\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d %5d %5d %5d %5d %5d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Number MDR MP
====== === ==
123321 8 3
7739 8 3
893 2 3
899998 0 2
 
MDR 1 2 3 4 5
=== ===========================
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>
 
===Similar===
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">pdd</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%2d"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">product</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">)))</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Product of the decimal digits of 1..100:\n%s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</span><span style="color: #0000FF;">),</span><span style="color: #000000;">pdd</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Product of the decimal digits of 1..100:
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
2 4 6 8 10 12 14 16 18 0
3 6 9 12 15 18 21 24 27 0
4 8 12 16 20 24 28 32 36 0
5 10 15 20 25 30 35 40 45 0
6 12 18 24 30 36 42 48 54 0
7 14 21 28 35 42 49 56 63 0
8 16 24 32 40 48 56 64 72 0
9 18 27 36 45 54 63 72 81 0
</pre>
 
=={{header|PL/I}}==
===version 1===
{{incomplete|PL/I|Missing second half of task!}}
<langsyntaxhighlight lang="pli">multiple: procedure options (main); /* 29 April 2014 */
 
declare n fixed binary (31);
Line 1,964 ⟶ 2,583:
end;
 
end multiple;</langsyntaxhighlight>
{{out}}
<pre>N= 123321 MDR= 8 MP= 3;
Line 1,972 ⟶ 2,591:
 
===version 2===
<langsyntaxhighlight lang="pli"> mdrt: Proc Options(main);
Dcl (x,p,r) Bin Fixed(31);
Put Edit('number persistence multiplicative digital root')(Skip,a);
Line 2,027 ⟶ 2,646:
End;
End;
End;</langsyntaxhighlight>
{{out}}
<pre>number persistence multiplicative digital root
Line 2,051 ⟶ 2,670:
=={{header|Python}}==
===Python: Inspired by the solution to the [[Digital root#Python|Digital root]] task===
<langsyntaxhighlight lang="python">try:
from functools import reduce
except:
Line 2,075 ⟶ 2,694:
print('\nMP: [n0..n4]\n== ========')
for mp, val in sorted(table.items()):
print('%2i: %r' % (mp, val[:5]))</langsyntaxhighlight>
 
{{out}}
Line 2,100 ⟶ 2,719:
===Python: Inspired by the [[Digital_root/Multiplicative_digital_root#More_Efficient_Version|more efficient version of D]].===
Substitute the following function to run twice as fast when calculating mdroot(n) with n in range(1000000).
<langsyntaxhighlight lang="python">def mdroot(n):
count, mdr = 0, n
while mdr > 9:
Line 2,109 ⟶ 2,728:
mdr = digitsMul
count += 1
return count, mdr</langsyntaxhighlight>
 
{{out}}
(Exactly the same as before).
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ abs 1 swap
[ base share /mod
rot * swap
dup 0 = until ]
drop ] is digitproduct ( n --> n )
[ 0 swap
[ dup base share > while
dip 1+
digitproduct again ] ] is mdr ( n --> n n )
[ dup mdr
rot echo
say ": "
swap echo
say ", "
echo cr ] is task.1 ( n --> )
[ times
[ i^ [] swap dup rot
[ unrot dup mdr nip
swap dip
[ over = ]
swap iff
[ rot over join ]
else rot
dip 1+
dup size 5 = until ]
i^ echo say " : "
echo cr 2drop ] ] is task.2 ( n --> )
' [ 123321 7739 893 899998 ] witheach task.1
cr
10 task.2</syntaxhighlight>
 
{{out}}
 
<pre>123321: 3, 8
7739: 3, 8
893: 3, 2
899998: 2, 0
 
0 : [ 0 20 30 40 45 ]
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|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(define (digital-product n)
(define (inr-d-p m rv)
Line 2,137 ⟶ 2,812:
(for ((MDR (in-range 10)))
(define (has-mdr? n) (define-values (mdr mp) (mdr/mp n)) (= mdr MDR))
(printf "~a\t~a~%" MDR (for/list ((_ 5) (n (sequence-filter has-mdr? (in-naturals)))) n)))</langsyntaxhighlight>
{{out}}
<pre>Number MDR mp
Line 2,158 ⟶ 2,833:
8 (8 18 24 29 36)
9 (9 19 33 91 119)</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub multiplicative-digital-root(Int $n) {
return .elems - 1, .[.end]
given cache($n, {[*] .comb} ... *.chars == 1)
}
 
for 123321, 7739, 893, 899998 {
say "$_: ", .&multiplicative-digital-root;
}
 
for ^10 -> $d {
say "$d : ", .[^5]
given (1..*).grep: *.&multiplicative-digital-root[1] == $d;
}</syntaxhighlight>
{{out}}
<pre>123321: 3 8
7739: 3 8
893: 3 2
899998: 2 0
0 : 10 20 25 30 40
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|Red}}==
<syntaxhighlight lang="rebol">Red ["Multiplicative digital root"]
 
mdr: function [
"Returns a block containing the mdr and persistence of an integer"
n [integer!]
][
persistence: 0
while [n > 10][
product: 1
m: n
while [m > 0][
product: m % 10 * product
m: to-integer m / 10
]
persistence: persistence + 1
n: product
]
reduce [n persistence]
]
 
foreach n [123321 7739 893 899998][
result: mdr n
print [pad n 6 "has multiplicative persistence" result/2 "and MDR" result/1]
]
 
print [newline "First five numbers with MDR of"]
 
repeat i 10 [
prin rejoin [i - 1 ": "]
hits: n: 0
while [hits < 5][
if i - 1 = first mdr n [
prin pad n 5
hits: hits + 1
]
n: n + 1
]
prin newline
]</syntaxhighlight>
{{out}}
<pre>
123321 has multiplicative persistence 3 and MDR 8
7739 has multiplicative persistence 3 and MDR 8
893 has multiplicative persistence 3 and MDR 2
899998 has multiplicative persistence 2 and MDR 0
 
First five numbers with MDR of
0: 0 20 30 40 45
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|REXX}}==
===idomatic version===
<langsyntaxhighlight lang="rexx">/*REXX pgmprogram finds the persistence and multiplicative digital root of some #'snumbers.*/
numeric digits 100 /*increase the number of digits.decimal digits*/
parse arg x /*getobtain someoptional numbersarguments from the C.L. CL*/
if x='' | x="," then x=123321 7739 893 899998 /*useNot defaultsspecified? if noneThen specifieduse the default.*/
say center('number', 8) ' persistence multiplicative digital root'
say copies('─' , 8) ' ─────────── ───────────────────────────'
/* [↑] the title and separator. */
do j=1 for words(x); n=word(x, j) /*process each number in the X list.*/
parse value mdr MDR(n) with mp mdr /*obtain the persistence and the MDR. */
say right(n,8) center(mp,13) center(mdr,30) /*display #a number, mp persistence, mdr MDR.*/
end /*j*/ /* [↑] show MP and& MDR for each #number. */
say copies('─' , 8) ' ─────────── ───────────────────────────'
say; target=5
say; say; target=5
say 'MDR first ' target " numbers that have a matching MDR"
say '═══ ═══════════════════════════════════════════════════'
 
do k=0 for 10; hits=0; _= /*show #'s that have an MDR of K.*/
do m=k=0 untilfor 10; hits=0; _=target /*findshow targetnumbers #sthat withhave an MDR of K. */
ifdo word(mdr(m),2)\==k thenuntil hits==target iterate /*isfind thetarget MDRnumbers what'swith an MDR wanted?of K.*/
hits=hits+1; if _=spaceword(_ MDR(m'),' 2)\==k then iterate /*yes,is wethis gotthe MDR that's wanted? a hit, add to list.*/
end /*m*/ hits=hits + 1; _=space(_ m',') /*yes, [↑]we builtgot a listhit, of MDRsadd =to kthe list. */
say " "k':end /*m*/ ['strip(_,,',')"]" /*display the[↑] Kbuilt a (mdr)list andof listMDRs that = K. */
endsay " /*"k*/': ['strip(_, , ',')"]" /*display the K /* [↑] (MDR) done withand the K mdr list. */
exit end /*k*/ /*stick a[↑] fork indone it,with we'rethe done K MDR list. */
say '═══ ═══════════════════════════════════════════════════'
/*──────────────────────────────────MDR subroutine──────────────────────*/
exit 0 /*stick a fork in it, we're all done. */
mdr: procedure; parse arg y; y=abs(y) /*get the number and find the MDR*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
do p=1 until y<10 /*find multiplicative digRoot (Y)*/
MDR: procedure; parse arg y; y=abs(y) /*get the number and determine the MDR.*/
parse var y 1 r 2; do k=2 to length(y); r=r*substr(y,k,1); end; y=r
end /*p*/ do p=1 until /*wash,y<10; rinse, repeat ··· parse var y r */2
return p r do k=2 to length(y); r=r /*return thesubstr(y, persistencek, and MDR.*/</lang>1)
end /*k*/
'''output''' &nbsp; when using the default inputs:
y=r
end /*p*/ /* [↑] wash, rinse, and repeat ··· */
return p r /*return the persistence and the MDR. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
number persistence multiplicative digital root
Line 2,197 ⟶ 2,968:
893 3 2
899998 2 0
──────── ─────────── ───────────────────────────
 
 
MDR first 5 numbers that have a matching MDR
Line 2,210 ⟶ 2,983:
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
═══ ═══════════════════════════════════════════════════
</pre>
 
===ultra-fast version===
This fast version can handle a target of five hundred numbers with ease for the 2<sup>nd</sup> part of the task's requirement.
<langsyntaxhighlight lang="rexx">/*REXX pgmprogram finds the persistence and multiplicative digital root of some #'snumbers.*/
numeric digits 2000 /*increase the number of digits.decimal digits*/
parse arg target x; if \datatype(target,'W') then target=25 /*default?obtain optional arguments from the CL*/
if x=\datatype(target, 'W') then xtarget=12332125 7739 893 899998 /*use the defaults for X/*Not specified? Then use the default.*/
if x='' | x="," then x=123321 7739 893 899998 /* " " " " " " */
say center('number',8) ' persistence multiplicative digital root'
say copies('─' ,8) ' ─────────── ───────────────────────────'
/* [↑] the title and the separator. */
do j=1 for words(x); n= abs( word(x, j)) ) /*process each #number in the list. */
parse value mdr MDR(n) with mp mdr /*obtain the persistence and the MDR. */
say right(n,8) center(mp,13) center(mdr,30) /*display #the number, mppersistence, mdrMDR.*/
end /*j*/ /* [↑] show MP and MDR for each #number.*/
say copies('─' ,8) ' ─────────── ───────────────────────────'
say /* [↓] show a blank & title line.*/
say; say /* [↓] show a blank and the title line.*/
say 'MDR first ' target " numbers that have a matching MDR"
say '═══ ' copies("═",(target+(target+1)**2)%2) /*display a sepseparator line (for title).*/
 
do k=0 for 9; hits= 0; _= /*show #'snumbers that have an MDR of K. */
_=
if k==7 then _=@7; else /*handle special seven case. */
if k==7 then _= @7 /*handle the special case of seven. */
else do m=k until hits==target /*find target numbers with an MDR of K.*/
parse var m '' -1 ? /*obtain the right─most digit of M. */
if k\==0 then if ?==0 then iterate
if k==5 then if ?//2==0 then iterate
if k==1 then m= copies(1, hits+1)
else if MDR(m, 1)\==k then iterate
hits= hits + 1 /*got a hit, add to the list*/
_= space(_ m) /*elide superfluous blanks. */
if k==3 then do; o=strip(m, 'T', 1) /*strip trailing ones from M*/
if o==3 then m= copies(1, length(m))3 /*make a new M.*/
else do; t= pos(3, m) - 1 /*position of 3 */
m= overlay(3, translate(m, 1, 3), t)
end /* [↑] shift the "3" 1 place left.*/
m= m - 1 /*adjust for DO index increment.*/
end /* [↑] a shortcut to adj DO index*/
end /*m*/ /* [↑] built a list of MDRs = K */
 
say " "k': ['_"]" do m=k until hits==target /*finddisplay targetthe #s withK an (MDR) of Kand the list. */
if k==3 then ?@7=right translate(m_,1) 7, k) /*save for later, a special "7" /*obtain right-most digit of Mcase. */
end if /*k\==0*/ then if ?==0/* [↑] done with the K MDR list. then iterate*/
if k==5 then if ?//2==0 then iterate
if k==1 then m=copies(1,hits+1)
else if mdr(m,1)\==k then iterate
hits=hits+1; _=space(_ m) /*yes, we got a hit, add to list.*/
 
@.= if k==3 then do; o=strip(m,'T',1) /*strip trailing[↓] handle MDR of "9" special. ones*/
_= translate(@7, 9, 7) if o==3 then m=copies(1,length(m))3 /*maketranslate newstring for MMDR of nine. */
@9= translate(_, , ',') else/*remove do;trailing commas from t=pos(3,m)-1 /*position ofnumbers. 3*/
@3= m=overlay(3,translate(m,1,3),t) /*assign null string before building. */
end /* [↑] shift the "3" 1 place left*/
m=m-1 /*adjust for DO index advancement*/
end /* [↑] a shortcut to do DO index*/
end /*m*/ /* [↑] built a list of MDRs = k */
 
do j=1 for words(@9) say " "k': ['_"]" /*displayprocess theeach number Kfor (mdr)MDR 9 and listcase.*/
if k_==3 space( then @7=translate(_ word(@9,7 j),k , 9), 0) /*saveelide forall later, special"9"s 7 case using SPACE(x,0).*/
L= length(_) + 1 end /*k*/ /*use [↑]a "fudged" donelength withof the Knumber. mdr list.*/
@. new= /*these [↓]are the handlenew MDRnumbers of 9(so specialfar). */
_=translate(@7,9,7) /*translate a string for MDR 9. */
@9=translate(_,,',') /*remove trailing commas from #'s*/
@3= /*assine null string before build*/
do j=1 for words(@9) /*process each number for MDR 9. */
_=space(translate(word(@9,j),,9),0) /*remove "9"s using SPACE(x,0)*/
L=length(_)+1 /*use a "fudged" length of the #.*/
new= /*this is the new numbers so far.*/
do k=0 for L; q=insert(3,_,k) /*insert the 1st "3" into the #*/
do i=k to L; z=insert(3,q,i) /* " " 2nd "3" " " "*/
if @.z\=='' then iterate /*if already define, ignore the #*/
@.z=z; new=z new /*define it, and then add to list*/
end /*i*/ /* [↑] end of 2nd insertion of 3*/
end /*k*/ /* [↑] " " 1st " " "*/
@3=space(@3 new) /*remove blanks, then add to list*/
end /*j*/ /* [↑] end of insertion of "3"s.*/
 
a1=@9; a2=@3; @= do k=0 for L; q= insert(3, _, k) /*defineinsert threethe strings for1st "3" into the merge.number*/
do i=k to L; z= insert(3, q, i) /* " " 2nd "3" /* [↓] " " merge two lists, 3s" & 9s.*/
do while a1if @.z\=='' & a2\==''then iterate /*processif whilealready thedefine, listsignore the ¬emptynumber.*/
@.z= z; new= z new /*define it, and then add to the list.*/
x=word(a1,1); y=word(a2,1); if x=='' | y=='' then leave /*empty?*/
if x<y then do;end /*i*/ @=@ x; a1=delword(a1,1,1); end /*add X[↑] end of 2nd insertion of "3".*/
end /*k*/ else do; @=@ y; a2=delword(a2,1,1); end /*add Y.[↑] " " 1st " " " */
 
end /*while ···*/ /* [+] only process just 'nuff. */
@3=subword space(@,1,target3 new) /*elideremove theblanks, last trailingthen comma.add to the list.*/
say " "9': end /*j*/ ['@"]" /*display the[↑] 9end of (mdr)insertion andof listthe "3"s. */
exit@= /*stick a[↓] fork inmerge ittwo lists, we're done3s and 9s. */
a1= @9; a2= @3 /*define some strings for the merge. */
/*──────────────────────────────────MDR subroutine──────────────────────*/
do while a1\=='' & a2\=='' /*process while the lists aren't empty.*/
mdr: procedure; parse arg y,s /*get the number and find the MDR*/
do p x=1 word(a1, until1); y<10= word(a2, 1) /*obtain the 1st /*findword multiplicativein digRootA1 (Y)& A2 lists.*/
if x=='' | y=='' then leave /*are X or Y empty? */
parse var y 1 r 2; do k=2 to length(y); r=r*substr(y,k,1); end; y=r
end /*p*/ if x<y then do; @= @ x; a1= delword(a1, 1, 1); end /*wash, rinse, repeat ··· add X to the @ list*/
if s==1 then return r else do; @= @ y; a2= delword(a2, 1, 1); end /*return multiplicative" Y " " " dig" root.*/
end /*while*/ return p r /*return the[↑] persistence andonly MDRprocess just enough nums. */</lang>
 
;;;output''' &nbsp' when the using the input of: &nbsp; <tt> 34 </tt>
@= subword(@, 1, target) /*elide the last trailing comma in list*/
say " "9': ['@"]" /*display the "9" (MDR) and the list.*/
say '═══ ' copies("═",(target+(target+1)**2)%2) /*display a separator line (for title).*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
MDR: procedure; parse arg y,s; y= abs(y) /*get the number and determine the MDR.*/
do p=1 until y<10; parse var y r 2
do k=2 to length(y); r= r * substr(y, k, 1)
end /*k*/
y= r
end /*p*/ /* [↑] wash, rinse, and repeat ··· */
if s==1 then return r /*return multiplicative digital root. */
return p r /*return the persistence and the MDR. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 34 </tt>}}
<pre>
number persistence multiplicative digital root
Line 2,294 ⟶ 3,078:
893 3 2
899998 2 0
──────── ─────────── ───────────────────────────
 
 
MDR first 34 numbers that have a matching MDR
Line 2,307 ⟶ 3,093:
8: [8 18 24 29 36 38 42 46 49 63 64 66 67 76 77 79 81 83 88 92 94 97 99 118 124 129 136 138 142 146 149 163 164 166]
9: [9 19 33 91 119 133 191 313 331 911 1119 1133 1191 1313 1331 1911 3113 3131 3311 9111 11119 11133 11191 11313 11331 11911 13113 13131 13311 19111 31113 31131 31311 33111]
═══ ═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
</pre>
 
===Similar===
<syntaxhighlight lang="rexx">/*REXX pgm finds positive integers when shown in hex that can't be written with dec digs*/
parse arg n cols . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n = 100 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
w= 10 /*width of a number in any column. */
title= ' the product of the decimal digits of N, where N < ' n
say ' index │'center(title, 1 + cols*(w+1) ) /*display the title for the output. */
say '───────┼'center("" , 1 + cols*(w+1), '─') /* " a sep " " " */
$=; idx= 1 /*list of products (so far); IDX=index.*/
do #=1 for n; L= length(#) /*find products of the dec. digs of J. */
p= left(#, 1) /*use first digit as the product so far*/
do j=2 for L-1 until p==0 /*add an optimization when product is 0*/
p= p * substr(#, j, 1) /*multiply the product by the next dig.*/
end /*j*/
$= $ right(p, w) /*add the product ───► the $ list. */
if #//cols \== 0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*#*/ /*stick a fork in it, we're all done. */
 
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
say '───────┴'center("" , 1 + cols*(w+1), '─') /*display the foot sep for output. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
index │ the product of the decimal digits of N, where N < 100
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
1 │ 1 2 3 4 5 6 7 8 9 0
11 │ 1 2 3 4 5 6 7 8 9 0
21 │ 2 4 6 8 10 12 14 16 18 0
31 │ 3 6 9 12 15 18 21 24 27 0
41 │ 4 8 12 16 20 24 28 32 36 0
51 │ 5 10 15 20 25 30 35 40 45 0
61 │ 6 12 18 24 30 36 42 48 54 0
71 │ 7 14 21 28 35 42 49 56 63 0
81 │ 8 16 24 32 40 48 56 64 72 0
91 │ 9 18 27 36 45 54 63 72 81 0
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Digital root/Multiplicative digital root
 
load "stdlib.ring"
root = newlist(10, 5)
for r = 1 to 10
for x = 1 to 5
root[r][x] = 0
next
next
root2 = list(10)
for y = 1 to 10
root2[y] = 0
next
see "Number MDR MP" + nl
num = [123321, 7739, 893, 899998]
digroot(num)
see nl
num = 0:12000
digroot(num)
see "First five numbers with MDR in first column:" + nl
for n1 = 1 to 10
see "" + (n1-1) + " => "
for n2 = 1 to 5
see "" + root[n1][n2] + " "
next
see nl
next
 
func digroot(num)
for n = 1 to len(num)
sum = 0
numold = num[n]
while true
pro = 1
strnum = string(numold)
for nr = 1 to len(strnum)
pro = pro * number(strnum[nr])
next
sum = sum + 1
numold = pro
numn = string(num[n])
sp = 6 - len(string(num[n]))
if sp > 0
for p = 1 to sp + 2
numn = " " + numn
next
ok
if len(string(numold)) = 1 and len(num) < 5
see "" + numn + " " + numold + " " + sum + nl
exit
ok
if len(string(numold)) = 1 and len(num) > 4
root2[numold+1] = root2[numold+1] + 1
if root2[numold+1] < 6
root[numold+1][root2[numold+1]] = num[n]
ok
exit
ok
end
next
</syntaxhighlight>
Output:
<pre>
Number MDR MP
123321 8 3
7739 8 3
893 2 3
899998 0 2
 
First five numbers with MDR in first column:
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>
 
===Similar===
<syntaxhighlight lang="ring">
load "stdlib.ring"
see "working..." + nl
see "Product of decimal digits of n:" + nl
 
row = 0
limit = 100
 
for n = 1 to limit
prod = 1
strn = string(n)
for m = 1 to len(strn)
prod = prod * number(strn[m])
next
see "" + prod + " "
row = row + 1
if row%5 = 0
see nl
ok
next
 
see "done..." + nl
</syntaxhighlight>
{{out}}
<pre>
working...
Product of decimal digits of n:
1 2 3 4 5
6 7 8 9 0
1 2 3 4 5
6 7 8 9 0
2 4 6 8 10
12 14 16 18 0
3 6 9 12 15
18 21 24 27 0
4 8 12 16 20
24 28 32 36 0
5 10 15 20 25
30 35 40 45 0
6 12 18 24 30
36 42 48 54 0
7 14 21 28 35
42 49 56 63 0
8 16 24 32 40
48 56 64 72 0
9 18 27 36 45
54 63 72 81 0
done...
</pre>
 
=={{header|RPL}}==
≪ 1 SWAP
'''DO''' 10 / LAST MOD ROT * RND SWAP FLOOR
'''UNTIL''' DUP NOT '''END''' DROP
≫ ''''MDGIT'''' STO
≪ 0 '''WHILE''' OVER 9 > '''REPEAT'''
1 + SWAP '''MDGIT''' SWAP '''END''' SWAP R→C
≫ ''''MDPR'''' STO
≪ { 123321 7739 893 899998 } → cases
≪ {} 1 cases SIZE '''FOR''' j cases j GET '''MDPR''' + '''NEXT'''
≫ ≫ ''''TASK1'''' STO
≪ 1 10 '''START''' { 0 0 0 0 0 } '''NEXT''' 10 →LIST 'tab' STO 50 'cnt' STO
1 99999 '''FOR''' j
j '''MDPR''' IM 1 + tab OVER GET
'''IF''' DUP 0 POS '''THEN'''
LAST j PUT 'tab' ROT ROT PUT cnt 1 -
'''IF''' DUP '''THEN''' 'cnt' STO '''ELSE''' 99999 'j' STO '''END'''
'''ELSE''' DROP2 '''END'''
'''NEXT''' tab
≫ ''''TASK2'''' STO
{{out}}
<pre>
2: { (3,8) (3,8) (3,2) (2,0) }
1: { { 10 20 25 30 40 }
{ 1 11 111 1111 11111 }
{ 2 12 21 26 34 }
{ 3 13 31 113 131 }
{ 4 14 22 27 39 }
{ 5 15 35 51 53 }
{ 6 16 23 28 32 }
{ 7 17 71 117 171 }
{ 8 18 24 29 36 }
{ 9 19 33 91 119 } }
</pre>
 
=={{header|Ruby}}==
{{works with|Ruby|2.14}}
<langsyntaxhighlight lang="ruby">def mdroot(n)
mdr, persist = n, 0
until mdr < 10 do
mdr = mdr.to_s.each_char.map(&:to_i)digits.inject(:*)
persist += 1
end
Line 2,329 ⟶ 3,329:
end
puts "", "MDR: [n0..n4]", "=== ========"
10.times{|i| puts "%3d: %p" % [i, counter[i].first(5)]}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,351 ⟶ 3,351:
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
</pre>
 
=={{header|Rust}}==
{{trans|D}}
<syntaxhighlight lang="rust>
// Multiplicative digital root
fn mdroot(n: u32) -> (u32, u32) {
let mut count = 0;
let mut mdr = n;
while mdr > 9 {
let mut m = mdr;
let mut digits_mul = 1;
while m > 0 {
digits_mul *= m % 10;
m /= 10;
}
mdr = digits_mul;
count += 1;
}
return (count, mdr);
}
 
fn main() {
println!("Number: (MP, MDR)\n====== =========");
for n in [123321, 7739, 893, 899998] {
println!("{:6}: {:?}", n, mdroot(n));
}
let mut table = vec![vec![0_u32; 0]; 10];
let mut n = 0;
while table.iter().map(|row| row.len()).min().unwrap() < 5 {
let (_, mdr) = mdroot(n);
table[mdr as usize].push(n);
n += 1;
}
println!("\nMDR First 5 with matching MDR\n=== =========================");
table.sort();
for a in table {
println!("{:2}: {:5}{:6}{:6}{:6}{:6}", a[0], a[0], a[1], a[2], a[3], a[4]);
}
}
</syntaxhighlight>{{out}}
<pre>
Number: (MP, MDR)
====== =========
123321: (3, 8)
7739: (3, 8)
893: (3, 2)
899998: (2, 0)
 
MDR First 5 with matching MDR
=== =========================
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>
 
Line 2,356 ⟶ 3,417:
{{works with|Scala|2.9.x}}
 
<langsyntaxhighlight Scalalang="scala">import Stream._
 
object MDR extends App {
Line 2,382 ⟶ 3,443:
.foreach{p => printf("%3s: [%s]\n",p._2,p._1.mkString(", "))}
 
}</langsyntaxhighlight>
 
{{out}}
Line 2,407 ⟶ 3,468:
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]</pre>
=={{header|Scheme}}==
{{works with|Chez Scheme}}
<syntaxhighlight lang="scheme">; Convert an integer into a list of its digits.
 
(define integer->list
(lambda (integer)
(let loop ((list '()) (int integer))
(if (< int 10)
(cons int list)
(loop (cons (remainder int 10) list) (quotient int 10))))))
 
; Return the product of the digits of an integer.
 
(define integer-product-digits
(lambda (integer)
(fold-left * 1 (integer->list integer))))
 
; Compute the multiplicative digital root and multiplicative persistence of an integer.
; Return as a cons of (mdr . mp).
 
(define mdr-mp
(lambda (integer)
(let loop ((int integer) (cnt 0))
(if (< int 10)
(cons int cnt)
(loop (integer-product-digits int) (1+ cnt))))))
 
; Emit a table of integer, multiplicative digital root, and multiplicative persistence
; for the example integers given. Example list ends with sequence A003001 from OEIS.
 
(printf "~16@a ~6@a ~6@a~%" "Integer" "Root" "Pers.")
(printf "~16@a ~6@a ~6@a~%" "===============" "======" "======")
(let rowloop ((intlist '(123321 7739 893 899998
0 10 25 39 77 679 6788 68889 2677889 26888999 3778888999 277777788888899)))
(when (pair? intlist)
(let* ((int (car intlist))
(mm (mdr-mp int)))
(printf "~16@a ~6@a ~6@a~%" int (car mm) (cdr mm))
(rowloop (cdr intlist)))))
 
; Emit a table of multiplicative digital root versus the first five integers having that MDR.
 
(newline)
(printf "~5@a ~a~%" "Root" "First five integers with that root")
(printf "~5@a ~a~%" "====" "==================================")
(let ((mdrslsts (make-vector 10 '())))
(do ((integer 0 (1+ integer)))
((>= (fold-left min 5 (vector->list (vector-map length mdrslsts))) 5))
(let ((mdr (car (mdr-mp integer))))
(when (< (length (vector-ref mdrslsts mdr)) 5)
(vector-set! mdrslsts mdr (append (vector-ref mdrslsts mdr) (list integer))))))
(do ((mdr 0 (1+ mdr)))
((>= mdr 10))
(printf "~5@a" mdr)
(for-each (lambda (int) (printf "~7@a" int)) (vector-ref mdrslsts mdr))
(newline)))</syntaxhighlight>
{{out}}
<pre> Integer Root Pers.
=============== ====== ======
123321 8 3
7739 8 3
893 2 3
899998 0 2
0 0 0
10 0 1
25 0 2
39 4 3
77 8 4
679 6 5
6788 0 6
68889 0 7
2677889 0 8
26888999 0 9
3778888999 0 10
277777788888899 0 11
 
Root First five integers with that root
==== ==================================
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|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func mdroot(n) {
var (mdr, persist) = (n, 0)
while (mdr >= 10) {
Line 2,431 ⟶ 3,580:
 
say "\nMDR: [n0..n4]\n=== ========"
10.times {|i| "%3d: %s\n".printf(i, counter{i}.first(5)) }</langsyntaxhighlight>
 
{{out}}
Line 2,457 ⟶ 3,606:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc mdr {n} {
if {$n < 0 || ![string is integer $n]} {
error "must be an integer"
Line 2,465 ⟶ 3,614:
}
return [list $i $n]
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts "Number: MP MDR"
puts [regsub -all . "Number: MP MDR" -]
foreach n {123321 7739 893 899998} {
Line 2,482 ⟶ 3,631:
for {set i 0} {$i < 10} {incr i} {
puts [format "%3d: (%s)" $i [join [lrange $accum($i) 0 4] ", "]]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,504 ⟶ 3,653:
8: (8, 18, 24, 29, 36)
9: (9, 19, 33, 91, 119)
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">// Only valid for n > 0 && base >= 2
fn mult(nn u64, base int) u64 {
mut n := nn
mut mult := u64(0)
for mult = 1; mult > 0 && n > 0; n /= u64(base) {
mult *= n % u64(base)
}
return mult
}
// Only valid for n >= 0 && base >= 2
fn multi_digital_root(n u64, base int) (int, int) {
mut m := u64(0)
mut mp := 0
for m = n; m >= u64(base); mp++ {
m = mult(m, base)
}
return mp, int(m)
}
const base = 10
fn main() {
size := 5
println("${'Number':20} ${'MDR':3} ${'MP':3}")
for n in [
u64(123321), 7739, 893, 899998,
18446743999999999999,
// From http://mathworld.wolfram.com/MultiplicativePersistence.html
3778888999, 277777788888899,
] {
mp, mdr := multi_digital_root(n, base)
println("${n:20} ${mdr:3} ${mp:3}")
}
println('')
mut list := [base][]u64{init: []u64{len: 0, cap:size}}
for cnt, n := size*base, u64(0); cnt > 0; n++ {
_, mdr := multi_digital_root(n, base)
if list[mdr].len < size {
list[mdr] << n
cnt--
}
}
println("${'MDR':3}: First")
for i, l in list {
println("${i:3}: $l")
}
}</syntaxhighlight>
 
{{out}}
<pre>
Number MDR MP
123321 8 3
7739 8 3
893 2 3
899998 0 2
18446743999999999999 0 2
3778888999 0 10
277777788888899 0 11
 
MDR: First
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|Wren}}==
{{trans|Go}}
{{libheader|Wren-big}}
{{libheader|Wren-fmt}}
The size of some of the numbers here is such that we need to use BigInt.
<syntaxhighlight lang="wren">import "./big" for BigInt
import "./fmt" for Fmt
 
// Only valid for n > 0 && base >= 2
var mult = Fn.new { |n, base|
var m = BigInt.one
while (m > BigInt.zero && n > BigInt.zero) {
var dm = n.divMod(base)
m = m * dm[1]
n = dm[0]
}
return m
}
 
// Only valid for n >= 0 && base >= 2
var multDigitalRoot = Fn.new { |n, base|
base = BigInt.new(base)
var m = n.copy()
var mp = BigInt.zero
while (m >= base) {
m = mult.call(m, base)
mp = mp.inc
}
return [mp, m.toSmall]
}
 
var base = 10
var size = 5
 
var tests = [
123321, 7739, 893, 899998,"18446743999999999999", 3778888999, "277777788888899"
]
 
var testFmt = "$20s $3s $3s"
Fmt.print(testFmt, "Number", "MDR", "MP")
for (test in tests) {
var n = BigInt.new(test)
var mpdr = multDigitalRoot.call(n, base)
Fmt.print(testFmt, n, mpdr[1], mpdr[0])
}
System.print()
 
var list = List.filled(base, null)
for (i in 0...base) list[i] = []
var cnt = size * base
var n = BigInt.zero
while (cnt > 0) {
var mpdr = multDigitalRoot.call(n, base)
var mdr = mpdr[1]
if (list[mdr].count < size) {
list[mdr].add(n)
cnt = cnt - 1
}
n = n.inc
}
Fmt.print("$3s: $s", "MDR", "First")
var i = 0
for (l in list) {
Fmt.print("$3d: $s", i, l.toString)
i = i + 1
}</syntaxhighlight>
 
{{out}}
<pre>
Number MDR MP
123321 8 3
7739 8 3
893 2 3
899998 0 2
18446743999999999999 0 2
3778888999 0 10
277777788888899 0 11
 
MDR: First
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|XPL0}}==
{{trans|ALGOL W}}
<syntaxhighlight lang "XPL0"> \Calculate the Multiplicative Digital Root (MDR) and
\ Multiplicative Persistence (MP) of N
procedure GetMDR ( N, MDR, MP );
integer N, MDR, MP, V;
begin
MP(0) := 0;
MDR(0) := abs( N );
while MDR(0) > 9 do begin
V := MDR(0);
MDR(0) := 1;
repeat
MDR(0) := MDR(0) * rem( V / 10 );
V := V / 10;
until V = 0;
MP(0) := MP(0) + 1;
end; \while_mdr_gt_9
end; \GetMDR
 
define RequiredMDRs = 5;
integer FirstFew ( 9+1, 1+RequiredMDRs );
integer MDRFound ( 9+1 );
integer TotalFound, FoundPos, RequiredTotal, N, I, V, L;
integer MDR, MP;
begin
\task test cases
Text(0, " N MDR MP^m^j" );
L := [ 123321, 7739, 893, 899998 ];
for N := 0 to 3 do begin
GetMDR( L(N), @MDR, @MP );
Format(8, 0); RlOut(0, float(L(N)));
Format(4, 0); RlOut(0, float(MDR));
Format(3, 0); RlOut(0, float(MP));
CrLf(0)
end; \for_N
\find the first 5 numbers with each possible MDR
begin
for I := 0 to 9 do MDRFound( I ) := 0;
TotalFound := 0;
RequiredTotal := 10 * RequiredMDRs;
N := -1;
while TotalFound < RequiredTotal do begin
N := N + 1;
GetMDR( N, @MDR, @MP );
if MDRFound( MDR ) < RequiredMDRs then begin
\Found another number with this MDR and haven't found enough
TotalFound := TotalFound + 1;
MDRFound( MDR ) := MDRFound( MDR ) + 1;
FirstFew( MDR, MDRFound( MDR ) ) := N
end \if_Found_another_MDR
end; \while_TotalFound_lt_RequiredTotal
\print the table of MDRs and numbers
Text(0, "MDR: [N0..N4]^m^j" );
Text(0, "=== ========^m^j" );
for V := 0 to 9 do begin
ChOut(0, ^ ); IntOut(0, V); Text(0, ": [");
for FoundPos := 1 to RequiredMDRs do begin
if FoundPos > 1 then Text( 0, ", " );
IntOut( 0, FirstFew( V, FoundPos ) )
end; \for_FoundPos
Text(0, "]^m^j")
end \for_v
end
end</syntaxhighlight>
{{out}}
<pre>
N MDR MP
123321 8 3
7739 8 3
893 2 3
899998 0 2
MDR: [N0..N4]
=== ========
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|zkl}}==
{{trans|Python}}
<langsyntaxhighlight lang="zkl">fcn mdroot(n){ // Multiplicative digital root
mdr := List(n);
while (mdr[-1] > 9){
Line 2,514 ⟶ 3,916:
}
return(mdr.len() - 1, mdr[-1]);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn mdroot(n){
count:=0; mdr:=n;
while(mdr > 9){
Line 2,528 ⟶ 3,930:
}
return(count, mdr);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">println("Number: (MP, MDR)\n======= =========");
foreach n in (T(123321, 7739, 893, 899998))
{ println("%7,d: %s".fmt(n, mdroot(n))) }
Line 2,543 ⟶ 3,945:
foreach mp in (table.keys.sort()){
println("%2d: %s".fmt(mp, table[mp][0,5])); //print first five values
}</langsyntaxhighlight>
{{out}}
<pre>
1,969

edits