digital root问题

问题阐述会是这样的:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

这其实是一个digital root的问题。

digital root的定义如下:

  The digital root (also repeated digital sum) of a non-negative integer is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.

For example, the digital root of 65,536 is 7, because 6 + 5 + 5 + 3 + 6 = 25 and 2 + 5 = 7.

编程题中一般会要求在O(1)时间算出一个数的digital root,这时候就不能用上述思想解答问题了。

通用公式:

 operatorname{dr}(n) = egin{cases}0 & mbox{if} n = 0, \ 9 & mbox{if} n 
eq 0, n equiv 0pmod{9},\ n {
m mod} 9 & mbox{if} n 
otequiv 0pmod{9}.end{cases} 或者是

 mbox{dr}(n) = 1 + ((n-1) {
m mod} 9).           

所有的原理其实和模运算以及同余定理有关:

考虑12345 =  1 × 10,000 + 2 × 1,000 + 3 × 100 + 4 × 10 + 5.

同时10 i= 9 + 1; 100 i= 99 + 1,所以又可以写成:

12,345 = 1 × (9,999 + 1) + 2 × (999 + 1) + 3 × (99 + 1) + 4 × (9 + 1) + 5.

展开后:

12,345 = (1 × 9,999 + 2 × 999 + 3 × 99 + 4 × 9) + (1 + 2 + 3 + 4 + 5).

这样便满足了数根的思想,计算数根的一次迭代,当然(1 + 2 + 3 + 4 + 5)=15 又可以接着迭代,总之是:

S^{1}(n)=S(n),  S^{m}(n)=S(S^{m-1}(n)), 	ext{for} mge2.

数根是模9的余数是因为 10 equiv 1pmod{9}, 因此 10^k equiv 1^k equiv 1pmod{9},这样便有acdot 100 equiv acdot 10 equiv apmod{9} ,也就有如下推论:

mbox{dr}(abc) equiv acdot 10^2 + bcdot 10 + c cdot 1 equiv acdot 1 + bcdot 1 + c cdot 1 equiv a + b + c pmod{9}

这里要强调为什么当数字是9的倍数时,dr(n)是9?

例如:18 = 10 + 9

$18 equiv 0  pmod{9}$

但 $10 + 9 equiv 1 + 8 pmod{9}$,莫着急,这只是表象, $1 + 8 = 9 equiv 0 pmod{9}$

所以9的倍数的数根也可以用(mod 9)运算,只不过由于数根只在1-9之间,所以为零时只要换成9即可,毕竟$9 equiv 0 pmod{9}$

至于

 mbox{dr}(n) = 1 + ((n-1) {
m mod} 9).      也是这个道理,数根只能在1-9之间,而(mod 9)的数域在0-8之间, 所以先对数字减1然后再补1即可折中等效了。

关键点是理解为什么由

$a = b + c$
$b equiv r_1 pmod{9} $
$c equiv r_2 pmod{9} $

可推导出:

$a equiv r_1 + r_2pmod{9}$

提示:把数写成 $n = mq + r $,依据一条推论:

推论   a≡b(mod m)的充要条件是a=mt+b(t为整数)。

表示对模m同余关系的式子叫做模m的同余式,简称同余。

参考资料:

digital root

同余定理

A NEAT NUMBER TRICK: DIGITAL ROOTS AND MODULO-9 ARITHMETIC

leetcode--add digits

原文地址:https://www.cnblogs.com/vin-yuan/p/5291214.html