算法竞赛入门经典(第二版) | 程序3-9 生成元 (UVa1583,Digit Generator)

Description

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

题目大意:如果x加x各位之和等于y,则称x是y的生成元。给定n,求最小生成元。无解则输出0.


最初思路:枚举所有小于n的数,但效率太低,每次遍历相同的数字,遍历结果却没有利用起来。
改进版:运用常量数组的知识。枚举1-10W的数,制作出一个常量数组,n的生成元直接去数组中找即可。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#define Max 100005	//因为C语言存放大量数据时可能有微小
误差,可能溢出,因此在题给允许的条件下,多定义几个,以5为宜。 

using namespace std ;

int main()
{
	int a[Max] ;				//定义常量数组 
	memset(a,0,sizeof(a)) ; 	//赋0 
	
	//生成常量数组 
	int sum = 0 ;
	for(int i = 0; i < Max ; i++) {
		int s = i ;				//s起到i的作用
		while(s) {				//将每位相加的结果存入sum
			sum += s%10 ;
			s /= 10 ;
		}
		sum += i ;				//最后加入i本身
		
		//因为是求最小生成元,因此为第一次生成的值。 
		if(a[sum] == 0)
			a[sum] = i ;
		sum = 0 ;
	} 
	
	//输入、输出。 
	int n ;
	while(scanf("%d",&n) != EOF) {
		cout << a[n] << endl ;
	}
	return 0 ;
}
发布了27 篇原创文章 · 获赞 16 · 访问量 1953

猜你喜欢

转载自blog.csdn.net/weixin_43899069/article/details/104277741