Problem Description
A number whose only prime factors are 2,3,5 or 7 is called a humble number. The sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, ... shows the first 20 humble numbers.
Write a program to find and print the nth element in this sequence
Write a program to find and print the nth element in this sequence
Input
The input consists of one or more test cases. Each test case consists of one integer n with 1 <= n <= 5842. Input is terminated by a value of zero (0) for n.
Output
For each test case, print one line saying "The nth humble number is number.". Depending on the value of n, the correct suffix "st", "nd", "rd", or "th" for the ordinal number nth has to be used like it is shown in the sample output.
Sample Input
1 2 3 4 11 12 13 21 22 23 100 1000 5842 0
Sample Output
The 1st humble number is 1. The 2nd humble number is 2. The 3rd humble number is 3. The 4th humble number is 4. The 11th humble number is 12. The 12th humble number is 14. The 13th humble number is 15. The 21st humble number is 28. The 22nd humble number is 30. The 23rd humble number is 32. The 100th humble number is 450. The 1000th humble number is 385875. The 5842nd humble number is 2000000000.
刚拿到这道题,我有连个方向,一个是从2,3,5,7中产生所有humble number,一个是去除所有非humble number。然而,后者还要判断一个数的因子是不是含有非2,3,5,7的素数,运算量太大,于是我开始考虑前一种选择。
如何从2,3,5,7中产生humble number 呢?就是用这四个数的乘积组成新的数就好了。pow(2,i)*pow(3,j)*pow(5,k)*pow(7,l) ,就是它。
i,j,k,l的取值应当限制在使得pow(2,i),pow(3,j),pow(5,k),pow(7,l)都不超过200000000的范围内,以减少运算量而不丢失应当考虑的情况。
同时还要注意本题的一个坑:
11,111等
12,112等
13,113等
后缀都是th,而不是st,nd,rd
要单独考虑!
AC 代码
#include <iostream>
#include <string>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
freopen("D:\\input.txt","r",stdin); //delete it!!
freopen("D:\\output.txt","w",stdout);
//set<int> A;
vector<double> A;
A.clear();
for(int i=0;i<31;i++)
{
for(int j=0;j<21;j++)
{
for(int k=0;k<15;k++)
{
for(int l=0;l<13;l++)
{
A.push_back(pow(2,i)*pow(3,j)*pow(5,k)*pow(7,l));
}
}
}
}
sort(A.begin(),A.end());
int n;
cin>>n;
int a,b,c;
string fix;
while(n)
{
a=n%10;
b=n/10;
c=b%10;
if((a==1&&c==1)||(a==2&&c==1)||(a==3&&c==1))
{
fix="th";
}
else if(n%10==1)
fix="st";
else if(n%10==2)
fix="nd";
else if(n%10==3)
fix="rd";
else
fix="th";
cout<<"The " <<n<<fix<<" humble number is "<<A[n-1]<<'.'<<endl;
cin>>n;
}
}