例题3-5 生成元(Digit Generator, ACM/ICPCSeoul 2005, UVa1583)

/*例题3-5 生成元(Digit Generator, ACM/ICPCSeoul 2005, UVa1583)

如果x加上x的各个数字之和得到y,就说x是y的生成元。给出n(1≤n≤100000),求最小生成元。无解输出0。例如,n=216,121,2005时的解分别为198,0,1979。

【分析】

本题看起来是个数学题,实则不然。假设所求生成元为m。不难发现m<n。换句话说,只需枚举所有的m<n,看看有没有哪个数是n的生成元。

可惜这样做的效率并不高,因为每次计算一个n的生成元都需要枚举n-1个数。有没有更快的方法?聪明的读者也许已经想到了:只需一次性枚举100000内的所有正整数m,标记“m加上m的各个数字之和得到的数有一个生成元是m”,最后查表即可。*/

#include<stdio.h>
#include<string.h>
#define maxn 100005
int ans[maxn];
int main() 
{
	int T, n;
	memset(ans, 0, sizeof(ans));//数组置0 
	for(int m = 1; m < maxn; m++) {  //枚举100005内的所有正整数m
		int x = m, y = m;
		while(x > 0) { y += x % 10; x /= 10; }//求m加上m的各个数字之和得到的数
		if(ans[y] == 0 || m < ans[y]) ans[y] = m;//满足条件就有一个生成元是m或0 
	}
	scanf("%d", &T);
	while(T--) {
		scanf("%d", &n);
		printf("%d\n", ans[n]);//直接查表输出 
	}
	return 0;
}

原文:

For a positive integer N, the digit-sum of N is defined as the sumof N itself and its digits. When M is the digitsum of N, we call N a generatorof M.

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 somenumbers have more than one generator. For example, the generators of 216 are198 and 207.

You are to write a program to find the smallest generator of thegiven integer.

Input

Your program is to read from standard input. The input consists of Ttest cases. The number of test cases T is given in the first line of the input.Each test case takes one line containing an integer N, 1 ≤ N ≤ 100, 000.

Output

Your program is to write to standard output. Print exactly one linefor each test case. The line is to contain a generator of N for each test case.If N has multiple generators, print the smallest. If N does not have anygenerators, print ‘0’.

Sample Input

3

216

121

2005

Sample Output

198

0

1979


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追梦2017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值