Digital root/Multiplicative digital root

From Rosetta Code
Revision as of 10:20, 11 April 2014 by rosettacode>Paddy3118 (New draft task and Python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Digital root/Multiplicative digital root is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number (N) is calculated rather like the Digital root except digits are multiplied:

  • Set MDR to N and MP to 0
  • While MDR has more than one digit:
  • Find a replacement MDR as the multiplication of the digits of the current MDR
  • Increment MP
  • Return MP and MDR
Task
  • Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
  • Tabulate MP versus the first five numbers having that MP, something like:
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]

Show all output on this page.

References

The On-Line Encyclopedia of Integer Sequences.

Python

<lang python>try:

   from functools import reduce

except:

   pass

def mdroot(n):

   'Multiplicative digital root'
   mdr = [n]
   while mdr[-1] > 9:
       mdr.append(reduce(int.__mul__, (int(dig) for dig in str(mdr[-1])), 1))
   return len(mdr) - 1, mdr[-1]

if __name__ == '__main__':

   print('Number: (MP, MDR)\n======  =========')
   for n in (123321, 7739, 893, 899998):
       print('%6i: %r' % (n, mdroot(n)))
       
   table, n = {i: [] for i in range(10)}, 0
   while min(len(row) for row in table.values()) < 5:
       mpersistence, mdr = mdroot(n)
       table[mdr].append(n)
       n += 1
   for val in table.values():
       del val[5:]
   print('\nMP: [n0..n4]\n==  ========')
   for mp_val in sorted(table.items()):
       print('%2i: %r' % mp_val)</lang>
Output:
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]