POJ-1316-Self Numbers

 

                                  Self Numbers
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 24891   Accepted: 13910

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. 

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.

Sample Input


Sample Output

1
3
5
7
9
20
31
42
53
64
 |
 |       <-- a lot more numbers
 |
9903
9914
9925
9927
9938
9949
9960
9971
9982
9993

问题分析:
题目要求输出1-10000之间的自我数。
显然该题的input size为10000,考虑到只给到了1s的运行时间,所以不能直接用暴力法去破解。

经过仔细观察,如果一个数a是另外一个数b的next number,那么b<=a-36(9999的next number为9999+36),所以我们可以减少算法的操作单元

所以写出如下代码:

 

 1 #include<iostream>
 2 using namespace std;
 3 int main()
 4 {
 5 int i;
 6 for(i=1;i<=10000;i++)
 7 {
 8 int j;
 9 for(j=i-36;j<i;j++)
10 {
11 if((j+j%10+(j/10)%10+(j/100)%10+(j/1000)%10)==i)
12 {
13 break;
14 }
15 }
16 if(j==i)cout<<i<<endl;
17 }
18 return 0;
19 }

 

 

 

 即将本来要从1开始的循环缩短为i-36,这样o(n^2)的复杂度就变成了o(n)的复杂度。

 

我们可以在做进一步的思考,为什么不用一个used数组将1-10000之间所有数的next number记录下来呢,这样就可以一个简单的循环直接输出结果就行了。

这样算法进一步得到改善,得到如下代码:

 

 

 1 #include<iostream>
 2 using namespace std;
 3 int used[10000+36]={0};
 4 int main()
 5 {
 6 int i;
 7 for(i=1;i<=10000;i++)
 8 {
 9 used[i+i%10+(i/10)%10+(i/100)%10+(i/1000)%10+(i/10000)%10]=1;
10 }
11 for(i=1;i<10000;i++)
12 {
13 if(used[i]==0) cout<<i<<endl; 
14 }
15 return 0;
16 }

 

 

如下为运行后poj给出的结果 第一行为法二。

 

posted @ 2018-08-04 21:33  记得每天写代码  阅读(147)  评论(0编辑  收藏  举报