题目Self Number
POJ-1316
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
实现思路:
所谓self number ,如果一个正数a能够写成另外一个数b和b的各个位上的数之和,那么a就不是self number。
使用排除法:找出不是self number的。
【1】取出各个位上的数值。
for(int i=0;i<10000;++i)
{
all_number[i]=i+1;//1-10000
qian[i]=all_number[i]/1000;//取出千位
bai[i]=all_number[i]%1000/100;//取出百位
shi[i]=all_number[i]%1000%100/10;//取出十位
ge[i]=all_number[i]%10;//取出个位
}
int mid[10000];
for(int i=0;i<10000;++i)//find the wrong example
mid[i]=qian[i]+bai[i]+shi[i]+ge[i]+all_number[i];
【2】使用标记。all_number 数组中如果有mid数组中的数,标记为0
for(int i=0;i<10000;++i)
{
for(int j=0;j<10000;++j)
if(mid[i]<10000&&mid[i]==all_number[j])
all_number[j]=0;//使用标记,标记出来wrong number
}
实现代码:
#include<iostream>
using namespace std;
int main()
{
int all_number[10000],ge[10000],shi[10000],bai[10000],qian[10000];
for(int i=0;i<10000;++i)
{
all_number[i]=i+1;//1-10000
qian[i]=all_number[i]/1000;//取出每一位
bai[i]=all_number[i]%1000/100;
shi[i]=all_number[i]%1000%100/10;
ge[i]=all_number[i]%10;
}
int mid[10000];
for(int i=0;i<10000;++i)//find the wrong example
{
mid[i]=qian[i]+bai[i]+shi[i]+ge[i]+all_number[i];
}
for(int i=0;i<10000;++i)
{
for(int j=0;j<10000;++j)
{
if(mid[i]<10000&&mid[i]==all_number[j])
{
all_number[j]=0;//使用标记,标记出来wrong number
}
}
}
for(int j=0;j<10000-1;++j)
{
if(all_number[j]!=0)
cout<<all_number[j]<<endl;//output
}
return 0;
}