文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。
水题,数学题,关于数字根和同余的。
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:这道应该算水题吧,毕竟暴力好像也可以解决,写解题报告是因为这道题让我想起了小学奥数啊,哈哈...很清晰地记得这个数字根问题。
把一个数字的各位相加得到一个和,这个和又是一个新的数,把这个数的各位再次相加又得到一个和,如此一直重复做,直到最后的数字之和是一位数。这个数就是原数除以9的余数,我们把这个余数称之为原数的"数字根"。这道题肯定没有告诉你数字根和各位相加对9取余是一样的啦,我这里就把算法也说了,嘎嘎。
代码很简单,不说了。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> #include <string.h> using namespace std; int main() { int root; string n; while(1) { cin >> n; if (n == "0") break; root = 0; for (int i = 0; i < n.length(); i++) { root += n[i] - '0'; } root %= 9; cout << (root == 0 ? 9 : root) << endl; } //system("pause"); return 0; } |