题目简介
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;
}
本文介绍了一种特殊数列——谦逊数序列,并提供了一个简洁高效的C++实现方案,用于找出序列中的第n个元素。通过初始化序列并使用循环筛选倍数的方法,确保找到的数仅由2、3、5或7作为质因数。
582

被折叠的 条评论
为什么被折叠?



