生成元 Digit Generator UVA-1583

目录

题目:

思路和代码:

注意:

相关知识点:define关键字


题目:

For a positive integer N, the digit-sum of N is defined as the sum of N itself and its digits. When M is the digitsum of N, we call N a generator of 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 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.

Input

Your program is to read from standard input. The input consists of T test 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 line for 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 any generators, print ‘0’.

Sample Input

3

216

121

2005

Sample Output

198

0

1979

 

思路和代码:

  • 自己的思路首先是从1开始到n一个一个算,直到找到一个生成元或者到n即没有。这个方法没有什么技巧,并且当输入多的时候需要的计算量也比较大。提交显示Time limit exceede
#include<stdio.h>
int main(){
	int T,n;
	scanf("%d",&T);
	while(T--){
		scanf("%d",&n);
		int i,x,y;
		for(i=1;i<n;i++){
			x=i;y=i;
			while(x>0){
				y += x%10;
				x/=10;
			}
			if(y==n) {printf("%d\n",i); break;}
			else if(i==n-1) printf("%d\n",0);
			else continue;	
		}
	}
}

 

看过书上之后觉得书上所说的方法效率确实高了不少。

  • 定义一个数组a记录1-100000所有的生成元,初始值为0.一次性枚举100000内的所有正整数m,标记“m加上m的各个数字之和得到的数n有一个生成元m”,将m赋值给a[n],最后 根据输入查表即可。
#include<stdio.h>
#include<string.h>
#define maxn 100005
int a[maxn];
int main(){
    int T,n;
    memset(a,0,sizeof(a));
    int i,x,y;
    for(i=1;i<maxn;i++){
        x=i;y=i;
        while(x>0){ y+=x%10; x/=10;}
        if(a[y]==0 || i<a[y]) a[y]=i;
    }
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        printf("%d\n",a[n]);
    }
    return 0;
}

注意:

  1. #define maxn 100005 常见错误 #define maxn=100005;  注意没有 "="和";"
  2. x为整数类型     当x<10    x/10=0
  3. scanf里的变量需要事先定义。
  4. 严格注意格式,输出一行后不要忘记\n换行。
  5. 第二个代码为书上所给,但for循环内的if语句i<a[y]这个条件感觉没必要,因为for是从小到大循环,如果a[y]不为零则之前那个元显然更小。

相关知识点:

  • define关键字

    • 好处:一次定义可以多处使用,如果这个值需要改变,只需要改变define定义的即可,不用逐个修改。
    • 无参宏定义(宏名后不加参数):
      • 格式   #define 标识符 字符串
      • #                代表这是一条预处理命令
      • define        为宏定义命令
      • 标识符       为定义的宏名
      • 字符串       可以是常数、表达式等
      • 如    #define maxn 100005

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值