题目:http://acm.hdu.edu.cn/showproblem.php?pid=1058
一个数的因子由2,3,5,7构成,则这个数为 humble number.。前20个1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27,输入n。输出第n个 humble number.
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.
思路:因为因子只有4个,所以可以dp[i]保存第i个数,dp[i+1]=min(dp[i]*2,dp[i]*3,dp[i]*5,dp[i]*7)输出格式注意,个位上是1,2,3且十位不为1的输出st,nd,rd。
#include<stdio.h>
#include<algorithm>
using namespace std;
int minnum(int a1, int a2, int a3, int a4)//求四个数的最小值
{
int a[5];
a[0] = a1; a[1] = a2; a[2] = a3; a[3] = a4;
sort(a, a + 4);
return a[0];
}
int main()
{
int dp[6000] = { 0 };
dp[1] = 1; int t2 = 1, t3 = 1, t5 = 1, t7 = 1;
for (int i = 2; i <= 5842; i++)
{
dp[i] = minnum(2 * dp[t2], 3 * dp[t3], 5 * dp[t5], 7 * dp[t7]);
if (dp[i] == 2 * dp[t2])
t2++;
if (dp[i] == 3 * dp[t3])
t3++;
if (dp[i] == 5 * dp[t5])
t5++;
if (dp[i] == 7 * dp[t7])
t7++;
}
int n;
while (~scanf("%d",&n)&&n!=0)
{
if (n % 10 == 1 && n % 100 != 11)
printf("The %dst humble number is %d.\n", n, dp[n]);
else if(n % 10 == 2 && n % 100 != 12)
printf("The %dnd humble number is %d.\n", n, dp[n]);
else if (n % 10 == 3 && n % 100 != 13)
printf("The %drd humble number is %d.\n", n, dp[n]);
else
printf("The %dth humble number is %d.\n", n, dp[n]);
}
return 0;
}