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. <br><br>Write a program to find and print the nth element in this sequence<br>
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.<br>
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.<br>
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.
题意:每个数都是由有限个1 2 3 5 7的乘积构成,求前二十个这样的数。
解题思路:每个数都可以分解成有限个2 3 5 7 的乘积,dp方程为 dp[i]=a[i]=min(a[p1]*2,a[p2]*3,a[p3]*5,a[p4]*7);
当a[p1]*2==a[i]时p1++ 以此类推a[p2]*3==a[i]时p2++;a[p3]*5==a[i]时 p3++;a[p4]*7==a[i]时 p4++;
感想:注意输出的时候用th,rd,还是nd。
代码:
<span style="font-size:14px;color:#996633;">#include<iostream>
#include<cstdlib>
#include<iomanip>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int min(int a,int b,int c,int d)
{
int m;
if(a>b) {m=a;a=b;b=m;}
if(a>c) {m=a;a=c;c=m;}
if(a>d) {m=a;a=d;d=m;}
if(b>c) {m=b;b=c;c=m;}
if(b>d) {m=b;b=d;d=m;}
if(c>d) {m=c;c=d;d=m;}
return a;
}
int main()
{
int n,i;
int p1,p2,p3,p4;
p1=p2=p3=p4=1;
int a[6000];
memset(a,0,sizeof(a));
a[1]=1;
for(i=2;i<=5900;i++)
{
a[i]=min(a[p1]*2,a[p2]*3,a[p3]*5,a[p4]*7);
if(a[p1]*2==a[i]) p1++;
if(a[p2]*3==a[i]) p2++;
if(a[p3]*5==a[i]) p3++;
if(a[p4]*7==a[i]) p4++;
}
while(cin>>n)
{
if(n==0) break;
if(n%10==1&&n%100!=11) cout<<"The "<<n<<"st humble number is "<<a[n]<<"."<<endl;
else if(n%10==2&&n%100!=12) cout<<"The "<<n<<"nd humble number is "<<a[n]<<"."<<endl;
else if(n%10==3&&n%100!=13) cout<<"The "<<n<<"rd humble number is "<<a[n]<<"."<<endl;
else cout<<"The "<<n<<"th humble number is "<<a[n]<<"."<<endl;
}
return 0;
}
</span>