POJ 1519 Digital Roots C++版

POJ题解 1919浏览

Description

The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.

For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

Input

The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

Output

For each integer in the input, output its digital root on a separate line of the output.

Sample Input

24
39
0

Sample Output

6
3

Slyar:这道应该算水题吧，毕竟暴力好像也可以解决，写解题报告是因为这道题让我想起了小学奥数啊，哈哈...很清晰地记得这个数字根问题。

网友最新评论 (8)

1. 小学奥数好有用啊..........
booky5年前 (2013-07-10)回复
2. root += n[i] - '0'；为什么还要-‘0’？
匿名7年前 (2012-04-29)回复
3. @ljf 呃...的确可能是你理解错了...N=a[n]a[n-1]…a[0]，M=a[0]+a[1]+…+a[n]
Slyar9年前 (2009-11-16)回复
4. @Slyar 这不证明了直接模9和求每位之和后再模9是一样的吗？ 还是我哪里理解错了~~~~
ljf9年前 (2009-11-16)回复
5. @ljf 呃，这是个证明... 设自然数N=a[n]a[n-1]…a[0]，其中a[0]，a[1]、…、a[n]分别是个位、十位、…上的数字，再设M=a[0]+a[1]+…+a[n]，求证：N≡M(mod 9). 证明： ∵ N=a[n]a[n-1]…a[0]=a[n]*10^n+a[n-1]*10^(n-1)+…+a[1]*10+a[0]. 又∵ 1≡1(mod 9), 10≡1(mod 9), 102≡1(mod 9), … 10n≡1(mod 9). 上面这些同余式两边分别同乘以a[0]、a[1]、a[2]、…、a[n]，再相加得： a[0]+a[1]*10+…+a[n]*10^n≡(a[0]+a[1]+…+a[n])(mod 9)， 即 N≡M(mod 9)
Slyar9年前 (2009-11-15)回复
6. @Slyar 这个数就是原数除以9的余数，我们把这个余数称之为原数的"数字根" 那么这句话怎么理解呢？
ljf9年前 (2009-11-15)回复
7. @ljf 每次模9和求和之后模9不是一样的...
Slyar9年前 (2009-11-15)回复
8. 怎么不直接模9呢，为什么先求了次和？
ljf9年前 (2009-11-15)回复