码迷,mamicode.com
首页 > 其他好文 > 详细

POJ-1316-Self Numbers

时间:2018-08-04 22:32:09      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:复杂度   lang   output   info   put   img   image   str   思考   

 

                                  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),所以我们可以减少算法的操作单元

所以写出如下代码:

#include<iostream>
using namespace std;
int main()
{
int i;
for(i=1;i<=10000;i++)
{
int j;
for(j=i-36;j<i;j++)
{
if((j+j%10+(j/10)%10+(j/100)%10+(j/1000)%10)==i)
{
break;
}
}
if(j==i)cout<<i<<endl;
}
return 0;
}

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

 

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

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

 

#include<iostream>
using namespace std;
int used[10000+36]={0};
int main()
{
int i;
for(i=1;i<=10000;i++)
{
used[i+i%10+(i/10)%10+(i/100)%10+(i/1000)%10+(i/10000)%10]=1;
}
for(i=1;i<10000;i++)
{
if(used[i]==0) cout<<i<<endl;
}
return 0;
}

 

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

技术分享图片

 

POJ-1316-Self Numbers

标签:复杂度   lang   output   info   put   img   image   str   思考   

原文地址:https://www.cnblogs.com/bo2000/p/9420158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!