EOJ 1277/Ulm Local 1996 Humble Numbers

题目简介


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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值