POJ-1316-Self Numbers

Posted bo2000

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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),所以我们可以减少算法的操作单元

所以写出如下代码:

#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的主要内容,如果未能解决你的问题,请参考以下文章

有没有人知道格式化“缩写”数字的好 javascript 片段?

系统入门深度学习,直击算法工程师m

用最少的代码实现 numbers.Real

我该如何解决这个代码?没有错误可能是错误代码 - javascript (array,numbers,max,min)

链表-Add Two Numbers

PAT 甲级 1069 The Black Hole of Numbers (20 分)(内含别人string处理的精简代码)