Problem Description
In 1949 the Indian mathematician D.R. Kaprekar discovered a class of numbers called self-numbers. For any positive integer n, define d(n) to be n plus the sum of the digits of n. (The d stands for digitadition, a term coined by Kaprekar.) For example, d(75) = 75 + 7 + 5 = 87. Given any positive integer n as a starting point, you can construct the infinite increasing sequence of integers n, d(n), d(d(n)), d(d(d(n))), .... For example, if you start with 33, the next number is 33 + 3 + 3 = 39, the next is 39 + 3 + 9 = 51, the next is 51 + 5 + 1 = 57, and so you generate the sequence
33, 39, 51, 57, 69, 84, 96, 111, 114, 120, 123, 129, 141, ...
The number n is called a generator of d(n). In the sequence above, 33 is a generator of 39, 39 is a generator of 51, 51 is a generator of 57, and so on. Some numbers have more than one generator: for example, 101 has two generators, 91 and 100. A number with no generators is a self-number. There are thirteen self-numbers less than 100: 1, 3, 5, 7, 9, 20, 31, 42, 53, 64, 75, 86, and 97.
33, 39, 51, 57, 69, 84, 96, 111, 114, 120, 123, 129, 141, ...
The number n is called a generator of d(n). In the sequence above, 33 is a generator of 39, 39 is a generator of 51, 51 is a generator of 57, and so on. Some numbers have more than one generator: for example, 101 has two generators, 91 and 100. A number with no generators is a self-number. There are thirteen self-numbers less than 100: 1, 3, 5, 7, 9, 20, 31, 42, 53, 64, 75, 86, and 97.
Input
No input for this problem.
Output
Write a program to output all positive self-numbers less than 10000 in increasing order, one per line
这个题目没有输入。。网上也有人打表做。。那个也太没意思了。。况且才不是真正的打表法
这个题目一开始卡了一下我主要在如何抽取一个整数的各位数值。后来用一个递归,(虽然说可以不用递归,但我觉得用递归,整个程序清爽很多)但是在控制变量上,我又有问题了,主要是由一个变量函数运行完一次就要清零,而我写的是递归函数,不能把清零写在函数体里,所以就设置了一个全局变量s,并且用了一个辅助函数fuzhu,来控制变量的清零。。。程序里还创建了一个Bool类型的数组,我试验了一下,如果不初始化数组的话,会出问题,所以可以用循环,也可以用memset函数把数组里的元素初始值都设置为true。。。要注意的就是这几点了。。
#include<stdio.h>
#include<cstring>
int s=0;
int fenjie(int n)
{
s=s+n%10;
if (n/10>0) {return fenjie(n/10);}
else {return s;}
}
int fuzhu(int m)
{
fenjie (m);
s=0;
}
int main()
{
bool gen[11000];
memset(gen,1,sizeof(gen));
for (int i=1;i<=10000;i++)
{
gen[fuzhu(i)+i]=false;
}
for (int j=1;j<=10000;j++)
{
if (gen[j]) {printf("%d\n",j);}
}
return 0;
}