题目大意:定义了一种数字Humble Number,他们的质因数只包含2、3、5、7中的一个或者几个,求第n个这样的数,1<=n<=5842.
解法:一看到这道题又在想DFS了,可是我写的不熟练,最后罢工。Google之,发现还是可以用穷举法解决的。先列出2000000000以内的所有Humble Number,然后再查表。输出的时候要注意下,尾数是1、2、3的和剩下的数字要区别对待,可是尾数是11、12、13又是不一样的。
参考代码:
#include<iostream>
#include<math.h>
#include<algorithm> using namespace std; int main(){
double seven,five,three,two;
int a,humber[5842]={0},n=0;
for(seven=1;seven<=2000000000;seven*=7){
for(five=1;seven*five<=2000000000;five*=5){
for(three=1;seven*five*three<=2000000000;three*=3){
for(two=1;seven*five*three*two<=2000000000;two*=2){
humber[n]=seven*five*three*two;
n++;
}
}
}
}
sort(humber,humber+5842);
while((cin>>a)&&a!=0){
if(a%10==1&&a%100!=11){ //!!! cout format
cout<<"The "<<a<<"st humble number is "<<humber[a-1]<<"."<<endl;
continue;
}
if(a%10==2&&a%100!=12){
cout<<"The "<<a<<"nd humble number is "<<humber[a-1]<<"."<<endl;
continue;
}
if(a%10==3&&a%100!=13){
cout<<"The "<<a<<"rd humble number is "<<humber[a-1]<<"."<<endl;
continue;
}
cout<<"The "<<a<<"th humble number is "<<humber[a-1]<<"."<<endl; }
return 0;
}