标签:
For a positive integer N <tex2html_verbatim_mark>, the digit-sum of N <tex2html_verbatim_mark>is defined as the sum of N <tex2html_verbatim_mark>itself and its digits. When M <tex2html_verbatim_mark>is the digitsum of N <tex2html_verbatim_mark>, we call N <tex2html_verbatim_mark>a generator of M <tex2html_verbatim_mark>.
For example, the digit-sum of 245 is 256 (= 245 + 2 + 4 + 5). Therefore, 245 is a generator of 256.
Not surprisingly, some numbers do not have any generators and some numbers have more than one generator. For example, the generators of 216 are 198 and 207.
You are to write a program to find the smallest generator of the given integer.
Your program is to read from standard input. The input consists of T <tex2html_verbatim_mark>test cases. The number of test cases T<tex2html_verbatim_mark>is given in the first line of the input. Each test case takes one line containing an integer N <tex2html_verbatim_mark>, 1N100, 000 <tex2html_verbatim_mark>.
Your program is to write to standard output. Print exactly one line for each test case. The line is to contain a generator of N <tex2html_verbatim_mark>for each test case. If N <tex2html_verbatim_mark>has multiple generators, print the smallest. If N <tex2html_verbatim_mark>does not have any generators, print 0.
The following shows sample input and output for three test cases.
3 216 121 2005
198 0 1979
这道题本身很简单,但直接枚举每个数字肯定会效率低下,预先处理打一张表效率会高很多。
#include <stdio.h> #include <string.h> #define MAXN 100000 int ans[MAXN]; int main() { int T, n; memset(ans, 0, sizeof(ans)); for(int m = 1; m < MAXN; m++) //init { int x = m, y = m; while(x > 0) { y += x % 10; x /= 10; } if(!ans[y] || m < ans[y]) ans[y] = m; } scanf("%d", &T); while(T--) { scanf("%d", &n); printf("%d\n", ans[n]); } return 0; }
标签:
原文地址:http://www.cnblogs.com/cuichen/p/4296769.html