原题:
Introduction to the problem
A well-known trick to know if an integer N is a multiple of nine is to compute
the sum S of its digits. If S is a multiple of nine, then so is N. This is a
recursive test, and the depth of the recursion needed to obtain the answer on N
is called the 9-degree of N.
Your job is, given a positive number N, determine if it is a multiple of nine
and,if it is, its 9-degree.
Description of the input
The input is a file such that each line contains a positive number. A line
containing the number 0 is the end of the input. The given numbers can contain
up to 1000 digits.
Description of the output
The output of the program shall indicate, for each input number, if it is a
multiple of nine, and in case it is, the value of its nine-degree. See the
sample output for an example of the expected formatting of the output.
Sample input:
999999999999999999999
9
9999999999999999999999999999998
0
Sample output
999999999999999999999 is a multiple of 9 and has 9-degree 3.
9 is a multiple of 9 and has 9-degree 1.
9999999999999999999999999999998 is not a multiple of 9.
在数学学院主页上下载的上一届校赛的这一题的题解.
我完全服了,很精彩!
// Problem A
// [url]http://acm.uva.es/p/v109/10922.html[/url]
// Solution by semiconductor
#include <cstdio>
#include <cstring>
using namespace std;
char buf[1001];
void
Solve(int s)
{
int deg = 1;
while ( s >= 10 ) {
int ns = 0;
while ( s ) {
ns += s % 10;
s /= 10;
}
s = ns;
++deg;
}
if ( s == 9 ) printf("%s is a multiple of 9 and has 9-degree %d.\n", buf, deg);
else printf("%s is not a multiple of 9.\n", buf);
}
int
main()
{
while ( scanf("%s", buf), strcmp(buf, "0") ) {
int s = 0;
for ( int i = 0; buf[i]; i++ ) s += buf[i] - '0';
Solve(s);
}
}
[ 此贴被yinx在2007-03-31 11:53重新编辑 ]