【HDU1058】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.
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.
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.
题目要求求只包含2、3、5、7因子的第n个数字,我们先预处理前5842个Humble Numbers,然后直接O(1)输出
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <set>
std::set<long long> s;
int main() {
long long aim = 2000000000LL;
long long now = 1, a[4] = { 2, 3, 5, 7 };
long long ans[6000];int tot = 1;
ans[tot]=1;
while (now != aim) {
for (int i = 0; i <= 3; i++) {
if (now * a[i] <= aim) s.insert(now * a[i]);
}
now = *std::upper_bound(s.begin(), s.end(), now);
ans[++tot]=now;
s.erase(now);
}
std::sort(ans+1,ans+tot+1);
int n;
while(scanf("%d",&n),n){
if (n%100>=11 && n%100<=13) printf("The %dth humble number is %d.\n", n, ans[n]);
else if (n % 10 == 1) printf("The %dst humble number is %d.\n", n, ans[n]);
else if (n % 10 == 2) printf("The %dnd humble number is %d.\n", n, ans[n]);
else if (n % 10 == 3) printf("The %drd humble number is %d.\n", n, ans[n]);
else printf("The %dth humble number is %d.\n", n, ans[n]);
}
return 0;
}
通过取出最小数字然后不断乘以2、3、5、7因子找后面的humble number,一直找第5842个数字
标签:humble,int,HDU1058,Humble,number,long,Numbers,test,include 来源: https://www.cnblogs.com/rign/p/10348394.html