digital root问题

时间:2023-03-09 04:04:31
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,这时候就不能用上述思想解答问题了。

通用公式:

digital root问题 或者是

digital root问题

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

考虑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 又可以接着迭代,总之是:

digital root问题

数根是模9的余数是因为 digital root问题 因此 digital root问题这样便有digital root问题 ,也就有如下推论:

digital root问题

这里要强调为什么当数字是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}$

至于

digital root问题     也是这个道理,数根只能在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_2\pmod{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