Total Submit: 12051 Accepted Submit: 2591
Background
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.
Example
Input
24 39 0
Output
6 3
Problem Source: Greater New York 2000
题目地址:http://acm.zju.edu.cn/show_problem.php?pid=1115
本题大意是对于给定的一个正数,对其各位数字相加。如果结果为个位数,则输出,反之对结果的各位数字相加,直至得到一个个位数的结果。
本题的关键在于不知道输入的数有多少位,所以不能用int型,只能用数组存储输入的数。对于数组要开多大也不清楚,我开到511后还是提示Runtime Error SIGSEGV,直到1023后才AC。参考代码如下:
#include
<
stdio.h
>

int
main(
int
argc,
char
*
argv[])
...
{
int i, n;
char digit[1023];

while (1) ...{
gets(digit);
for (n = 0, i = 0; digit[i] != '/0'; i ++) n += digit[i] - 48;
if (!n) break;
while (n > 9) ...{
for (i = 0; n; n /= 10) i += n % 10;
n = i;
}
printf("%d ", n);
} 
return 0;
}
附:SIGSEGV in FAQ (http://acm.zju.edu.cn/faq.php)
Q:What does SIGSEGV in Runtime Error stand for?
A:The following messages will not be shown to you in contest. Here we just provide some tips:
SIGSEGV --- Segment Fault. The possible cases of your encountering this error are:
- 1.buffer overflow --- usually caused by a pointer reference out of range.
- 2.stack overflow --- please keep in mind that the default stack size is 8192K.
- 3.illegal file access --- file operations are forbidden on our judge system.
SIGFPE --- Divided by 0
SIGBUS --- Hardware Error. //please contact us
SIGABRT --- Programme aborted before it should be finished.
man 7 signal under Linux for more information
本文介绍了一个计算数字根的算法,即对于给定的任意正整数,通过不断累加其各个位上的数字直至结果为个位数的过程。文章提供了一段使用C语言实现的示例代码,并针对运行时错误SIGSEGV进行了说明。
5148

被折叠的 条评论
为什么被折叠?



