题目简介
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.
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.
说明
我觉得这题我的写法应该能算简洁……这类题似乎都有种核心思想:“如果一个数满足特性p,那么它的倍数一定也满足特性p”。当然这对特性p也是有要求的。
一旦条件成立,就可以用“初始化前几项->循环筛倍数->符合条件则计数器自增”的套路来做了。
#include <cstdio>
#include <algorithm>
using namespace std;
int h[5843];
void init()
{
int a, b, c, d, p1, p2, p3, p4;
p1 = p2 = p3 = p4 = h[1] = 1;
for (int i = 2; i <= 5843; ++i){
h[i] = min(min(a = h[p1]*2, b = h[p2]*3), min(c = h[p3]*5, d = h[p4]*7));
if (h[i] == a) ++p1;
if (h[i] == b) ++p2;
if (h[i] == c) ++p3;
if (h[i] == d) ++p4;
}
}
int main(){
int n;
init();
while(~scanf("%d", &n) && n){
printf("The %d", n);
if (n % 10 == 1 && n % 100 != 11) printf("st");
else if (n % 10 == 2 && n % 100 != 12) printf("nd");
else if (n % 10 == 3 && n % 100 != 13) printf("rd");
else printf("th");
printf(" humble number is %d.\n", h[n]);
}
return 0;
}