Digital root/Multiplicative digital root: Difference between revisions
Digital root/Multiplicative digital root (view source)
Revision as of 17:24, 9 April 2024
, 1 month agoAdded Easylang
(Add Red) |
(Added Easylang) |
||
(9 intermediate revisions by 8 users not shown) | |||
Line 42:
=={{header|11l}}==
{{trans|Python}}
<
V count = 0
V mdr = n
Line 73:
L(val) table
print(‘#2: ’.format(L.index), end' ‘’)
print(val[0.<5])</
{{out}}
Line 102:
The solution uses the Package "Generic_Root" from the additive digital roots [[http://rosettacode.org/wiki/Digital_root#Ada]].
<
procedure Multiplicative_Root is
Line 148:
TIO.New_Line;
end loop;
end Multiplicative_Root;</
{{out}}
Line 172:
=={{header|ALGOL 68}}==
<
# structure to hold the results of calculating the digital root & persistence #
MODE DR = STRUCT( INT root, INT persistence );
Line 241:
print md root( 899998 );
tabulate mdr( 5 )
END</
{{out}}
<pre>
Line 263:
=={{header|ALGOL W}}==
<
% calculate the Multiplicative Digital Root (mdr) and Multiplicative Persistence (mp) of n %
procedure getMDR ( integer value n
Line 328:
end
end.</
{{out}}
<pre>
Line 351:
=={{header|AWK}}==
<
BEGIN {
Line 426:
} # for pos
} # tabulateMdr</
{{out}}
<pre>
Line 448:
=={{header|Bracmat}}==
<
& ( MP/MDR
= prod L n
Line 493:
& put$\n
)
);</
{{out}}
<pre>123321 : (3.8)
Line 511:
=={{header|C}}==
<syntaxhighlight lang="c">
#include <stdio.h>
Line 570:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 593:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 631:
Console.WriteLine(" {0} : [{1}]", i, string.Join(", ", table[i]));
}
}</
{{out}}
<pre>123321 has multiplicative persistence 3 and multiplicative digital root 8
Line 649:
=={{header|C++}}==
<
#include <iomanip>
#include <map>
Line 709:
return system( "pause" );
}
</syntaxhighlight>
{{out}}
<pre>
Line 736:
=={{header|CLU}}==
<
while n>0 do
yield(n//10)
Line 794:
stream$putl(po, "")
end
end start_up</
{{out}}
<pre> N MDR MP
Line 817:
=={{header|Common Lisp}}==
<
(defun mdr/p (n)
"Return a list with MDR and MP of n"
Line 842:
do (format t "~6@a: ~{~3@a ~}~%" el (mdr/p el)))
(format t "~%MDR: [n0..n4]~%")
(first-n-number-for-each-root 5))</
{{out}}
<pre>
Line 865:
=={{header|Component Pascal}}==
{{Works with| BlackBox Component Builder}}
<
MODULE MDR;
IMPORT StdLog, Strings, TextMappers, DevCommanders;
Line 935:
END MDR.
</syntaxhighlight>
Execute:
^Q MDR.Do 123321 7739 893 899998 ~
Line 963:
=={{header|D}}==
{{trans|Python}}
<
/// Multiplicative digital root.
Line 989:
foreach (const mp; table.byKey.array.sort())
writefln("%2d: %s", mp, table[mp].take(5));
}</
{{out}}
<pre>Number: (MP, MDR)
Line 1,012:
===Alternative Version===
<
uint digitsProduct(uint n) pure nothrow @nogc {
Line 1,045:
foreach (const mp; table.byKey.array.sort())
writefln("%2d: %s", mp, table[mp].take(5));
}</
===More Efficient Version===
<
/// Multiplicative digital root.
Line 1,083:
foreach (const mp; table.byKey.array.sort())
writefln("%2d: %s", mp, table[mp].take(5));
}</
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}}==
<
def mdroot(n), do: mdroot(n, 0)
Line 1,123 ⟶ 1,199:
Digital.task1([123321, 7739, 893, 899998])
Digital.task2</
{{out}}
Line 1,149 ⟶ 1,225:
=={{header|F_Sharp|F#}}==
<
// mdr. Nigel Galloway: June 29th., 2021
let rec fG n g=if n=0 then g else fG(n/10)(g*(n%10))
Line 1,156 ⟶ 1,232:
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>
Line 1,175 ⟶ 1,251:
</pre>
=={{header|Factor}}==
<
math.text.utils prettyprint sequences ;
IN: rosetta-code.multiplicative-digital-root
Line 1,205 ⟶ 1,281:
{ 123321 7739 893 899998 } [ print-mdr ] each nl first5-table ;
MAIN: main</
{{out}}
<pre>
Line 1,228 ⟶ 1,304:
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
!Implemented by Anant Dixit (Oct, 2014)
program mdr
Line 1,320 ⟶ 1,396:
end subroutine
</syntaxhighlight>
<pre>
Line 1,347 ⟶ 1,423:
=={{header|FreeBASIC}}==
<
Function multDigitalRoot(n As UInteger, ByRef mp As Integer, base_ As Integer = 10) As Integer
Line 1,398 ⟶ 1,474:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,427 ⟶ 1,503:
=={{header|Go}}==
<
import "fmt"
Line 1,481 ⟶ 1,557:
fmt.Printf(tableFmt, i, l)
}
}</
{{out}}
<pre>
Line 1,508 ⟶ 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.
<
import Data.Array
import Data.LazyArray
Line 1,548 ⟶ 1,624:
printMpMdrs [123321, 7739, 893, 899998]
putStrLn ""
printMdrNums 5</
{{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,574 ⟶ 1,650:
Works in both languages:
<
write(right("n",8)," ",right("MP",8),right("MDR",5))
every r := mdr(n := 123321|7739|893|899998) do
Line 1,597 ⟶ 1,673:
while m > 0 do c *:= 1(m%10, m/:=10)
return c
end</
{{out}}
Line 1,626 ⟶ 1,702:
First, we need something to split a number into digits:
<
1 2 3 3 2 1</
Second, we need to find their product:
<
36</
Then we use this inductively until it converges:
<
123321 36 18 8</
MP is one less than the length of this list, and MDR is the last element of this list:
<
3 8
(<:@#,{:) */@(10&#.inv)^:a: 7739
Line 1,648 ⟶ 1,724:
3 2
(<:@#,{:) */@(10&#.inv)^:a: 899998
2 0</
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):
<
0 10 20 25 30
1 11 111 1111 11111
Line 1,662 ⟶ 1,738:
7 17 71 117 171
8 18 24 29 36
9 19 33 91 119</
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,668 ⟶ 1,744:
=={{header|Java}}==
{{works with|Java|8}}
<
public class MultiplicativeDigitalRoot {
Line 1,718 ⟶ 1,794:
return new long[]{n, mdr, mp};
}
}</
<pre>NUMBER MDR MP
Line 1,739 ⟶ 1,815:
=={{header|jq}}==
<
def u: if condition then . else (next|u) end;
u;
Line 1,770 ⟶ 1,846:
end;
[[], 0] | tab;</
'''Example''':<
def neatly:
. as $in
Line 1,786 ⟶ 1,862:
"Tabulation",
"MDR: [n0..n4]",
(tabulate(5) | neatly)</
{{out}}
<
i : [MDR, MP]
Line 1,807 ⟶ 1,883:
7: [7,17,71,117,171]
8: [8,18,24,29,36]
9: [9,19,33,91,119]</
=={{header|Julia}}==
'''Function'''
<syntaxhighlight lang="julia">
function digitalmultroot{S<:Integer,T<:Integer}(n::S, bs::T=10)
-1 < n && 1 < bs || throw(DomainError())
Line 1,822 ⟶ 1,898:
return (pers, ds)
end
</syntaxhighlight>
'''Main'''
<syntaxhighlight lang="julia">
const bs = 10
const excnt = 5
Line 1,859 ⟶ 1,935:
println(join([@sprintf("%6d", dmr[i, j]) for j in 1:excnt], ","))
end
</syntaxhighlight>
{{out}}
Line 1,885 ⟶ 1,961:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<
fun multDigitalRoot(n: Int): Pair<Int, Int> = when {
Line 1,935 ⟶ 2,011:
println()
}
}</
{{out}}
Line 1,959 ⟶ 2,035:
=={{header|M2000 Interpreter}}==
{{trans|FreeBASIC}}
<
if n<0 then error "Negative numbers not allowed"
def decimal mdr, mp, nn
Line 2,010 ⟶ 2,086:
Print #-2, doc$
</syntaxhighlight>
{{out}}
<pre> 123321 mdr = 8 MP = 3
Line 2,030 ⟶ 2,106:
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
ClearAll[mdr, mp, nums];
mdr[n_] := NestWhile[Times @@ IntegerDigits[#] &, n, # > 9 &];
Line 2,040 ⟶ 2,116:
TableForm[Table[{i, Take[nums[[i + 1]], 5]}, {i, 0, 9}],
TableHeadings -> {None, {"MDR", "First 5"}}, TableDepth -> 2]
</syntaxhighlight>
{{out}}
Line 2,067 ⟶ 2,143:
=={{header|Nim}}==
{{trans|Python}}
<
proc mdroot(n: int): tuple[mp, mdr: int] =
Line 2,088 ⟶ 2,164:
for mp, val in table:
echo mp, ": ", val[0..4]</
{{out}}
Line 2,108 ⟶ 2,184:
=={{header|PARI/GP}}==
<
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))))</
{{out}}
<pre>%1 = [[3, 8], [3, 8], [3, 2], [2, 0]]
Line 2,118 ⟶ 2,194:
inspired by [[Worthwhile_task_shaving]] :-)<BR>
Brute force speed up GetMulDigits.
<
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}
Line 2,244 ⟶ 2,320:
readln;
{$ENDIF}
END.</
{{out|@TIO.RUN}}
<pre>
Line 2,281 ⟶ 2,357:
=={{header|Perl}}==
{{trans|D}}
<
use strict;
Line 2,308 ⟶ 2,384:
my @n = map { $i++ while (mdr($i))[1] != $target; $i++; } 1..5;
print " $target: [", join(", ", @n), "]\n";
}</
{{out}}
<pre>Number: (MP, MDR)
Line 2,332 ⟶ 2,408:
=={{header|PicoLisp}}==
<
"Returns the solutions in a list, i.e., '(MDR MP)"
(let MP 0
Line 2,367 ⟶ 2,443:
(tab Fmt "===" " " "======")
(for (I . S) *Solutions
(tab Fmt (dec I) ": " (glue ", " S)) ) )</
{{out}}
Line 2,391 ⟶ 2,467:
=={{header|Phix}}==
<!--<
<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>
Line 2,436 ⟶ 2,512:
<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>
<!--</
{{out}}
<pre>
Line 2,461 ⟶ 2,537:
===Similar===
<!--<
<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>
<!--</
{{out}}
<pre>
Line 2,484 ⟶ 2,560:
===version 1===
{{incomplete|PL/I|Missing second half of task!}}
<
declare n fixed binary (31);
Line 2,507 ⟶ 2,583:
end;
end multiple;</
{{out}}
<pre>N= 123321 MDR= 8 MP= 3;
Line 2,515 ⟶ 2,591:
===version 2===
<
Dcl (x,p,r) Bin Fixed(31);
Put Edit('number persistence multiplicative digital root')(Skip,a);
Line 2,570 ⟶ 2,646:
End;
End;
End;</
{{out}}
<pre>number persistence multiplicative digital root
Line 2,594 ⟶ 2,670:
=={{header|Python}}==
===Python: Inspired by the solution to the [[Digital root#Python|Digital root]] task===
<
from functools import reduce
except:
Line 2,618 ⟶ 2,694:
print('\nMP: [n0..n4]\n== ========')
for mp, val in sorted(table.items()):
print('%2i: %r' % (mp, val[:5]))</
{{out}}
Line 2,643 ⟶ 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).
<
count, mdr = 0, n
while mdr > 9:
Line 2,652 ⟶ 2,728:
mdr = digitsMul
count += 1
return count, mdr</
{{out}}
Line 2,659 ⟶ 2,735:
=={{header|Quackery}}==
<
[ base share /mod
rot * swap
Line 2,692 ⟶ 2,768:
' [ 123321 7739 893 899998 ] witheach task.1
cr
10 task.2</
{{out}}
Line 2,714 ⟶ 2,790:
=={{header|Racket}}==
<
(define (digital-product n)
(define (inr-d-p m rv)
Line 2,736 ⟶ 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)))</
{{out}}
<pre>Number MDR mp
Line 2,760 ⟶ 2,836:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
return .elems - 1, .[.end]
given cache($n, {[*] .comb} ... *.chars == 1)
Line 2,772 ⟶ 2,848:
say "$d : ", .[^5]
given (1..*).grep: *.&multiplicative-digital-root[1] == $d;
}</
{{out}}
<pre>123321: 3 8
Line 2,790 ⟶ 2,866:
=={{header|Red}}==
<
mdr: function [
Line 2,828 ⟶ 2,904:
]
prin newline
]</
{{out}}
<pre>
Line 2,851 ⟶ 2,927:
=={{header|REXX}}==
===idomatic version===
<
numeric digits 100 /*increase the number of decimal digits*/
parse arg x /*obtain optional arguments from the CL*/
Line 2,883 ⟶ 2,959:
y=r
end /*p*/ /* [↑] wash, rinse, and repeat ··· */
return p r /*return the persistence and the MDR. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 2,912 ⟶ 2,988:
===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.
<
numeric digits 2000 /*increase the number of decimal digits*/
parse arg target x /*obtain optional arguments from the CL*/
Line 2,993 ⟶ 3,069:
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. */</
{{out|output|text= when using the input of: <tt> 34 </tt>}}
<pre>
Line 3,021 ⟶ 3,097:
===Similar===
<
parse arg n cols . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n = 100 /*Not specified? Then use the default.*/
Line 3,042 ⟶ 3,118:
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
say '───────┴'center("" , 1 + cols*(w+1), '─') /*display the foot sep for output. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 3,061 ⟶ 3,137:
=={{header|Ring}}==
<
# Project : Digital root/Multiplicative digital root
Line 3,122 ⟶ 3,198:
end
next
</syntaxhighlight>
Output:
<pre>
Line 3,145 ⟶ 3,221:
===Similar===
<
load "stdlib.ring"
see "working..." + nl
Line 3,167 ⟶ 3,243:
see "done..." + nl
</syntaxhighlight>
{{out}}
<pre>
Line 3,193 ⟶ 3,269:
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.4}}
<
mdr, persist = n, 0
until mdr < 10 do
Line 3,215 ⟶ 3,329:
end
puts "", "MDR: [n0..n4]", "=== ========"
10.times{|i| puts "%3d: %p" % [i, counter[i].first(5)]}</
{{out}}
<pre>
Line 3,237 ⟶ 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 3,242 ⟶ 3,417:
{{works with|Scala|2.9.x}}
<
object MDR extends App {
Line 3,268 ⟶ 3,443:
.foreach{p => printf("%3s: [%s]\n",p._2,p._1.mkString(", "))}
}</
{{out}}
Line 3,293 ⟶ 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}}
<
var (mdr, persist) = (n, 0)
while (mdr >= 10) {
Line 3,317 ⟶ 3,580:
say "\nMDR: [n0..n4]\n=== ========"
10.times {|i| "%3d: %s\n".printf(i, counter{i}.first(5)) }</
{{out}}
Line 3,343 ⟶ 3,606:
=={{header|Tcl}}==
<
if {$n < 0 || ![string is integer $n]} {
error "must be an integer"
Line 3,351 ⟶ 3,614:
}
return [list $i $n]
}</
Demonstrating:
<
puts [regsub -all . "Number: MP MDR" -]
foreach n {123321 7739 893 899998} {
Line 3,368 ⟶ 3,631:
for {set i 0} {$i < 10} {incr i} {
puts [format "%3d: (%s)" $i [join [lrange $accum($i) 0 4] ", "]]
}</
{{out}}
<pre>
Line 3,390 ⟶ 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>
Line 3,397 ⟶ 3,736:
{{libheader|Wren-fmt}}
The size of some of the numbers here is such that we need to use BigInt.
<
import "./fmt" for Fmt
// Only valid for n > 0 && base >= 2
Line 3,457 ⟶ 3,796:
Fmt.print("$3d: $s", i, l.toString)
i = i + 1
}</
{{out}}
Line 3,481 ⟶ 3,820:
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}}
<
mdr := List(n);
while (mdr[-1] > 9){
Line 3,491 ⟶ 3,916:
}
return(mdr.len() - 1, mdr[-1]);
}</
<
count:=0; mdr:=n;
while(mdr > 9){
Line 3,505 ⟶ 3,930:
}
return(count, mdr);
}</
<
foreach n in (T(123321, 7739, 893, 899998))
{ println("%7,d: %s".fmt(n, mdroot(n))) }
Line 3,520 ⟶ 3,945:
foreach mp in (table.keys.sort()){
println("%2d: %s".fmt(mp, table[mp][0,5])); //print first five values
}</
{{out}}
<pre>
|