HDU 1058 & POJ 2247 Humble Number

来源:互联网 发布:如何做数据统计 编辑:程序博客网 时间:2024/06/05 21:49

Humble Numbers

Time Limit: 2000/1000 MS (Java/Others)   

Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 11842    Accepted Submission(s): 5138

Problem Description 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.

View Code
 1 /* 2   对于每一个humble number,肯定都可以表示成(2^e1)*(3^e2)*(5^e3)*(7^e4); 3   其中e1,e2,e3,e4均大于等于0.所以,对于任意一个humble number,无论乘上2, 4   3,5,7都还是humble number.所以只需先打表求出前5842个humble number即可。 5   这里打表有个规律,那就是用四个整型p1,p2,p3,p4分别表示2,3,5,7已经乘到几 6   了,也就是如果p1 == 5,意味着2,4,6,8都已经出现,当前应该乘以5了。 7    8   78MS    252K 9   */10 11 #include <iostream>12 #include <cstdio>13 #include <cstring>14 #include <algorithm>15 16 using namespace std;17 18 int n;19 int ary[6000];20 21 int cmp(int a,int b,int c,int d)22 {23     int temp = min(a,b);24     temp = min(temp,c);25     temp = min(temp,d);26     return temp;27 }28 29 int main()30 {31     ary[1] = 1;32     int p1 = 1,p2 = 1,p3 = 1,p4 = 1;33     for(int i=2; i<=5842; i++)34     {35         ary[i] = cmp(ary[p1]*2,ary[p2]*3,ary[p3]*5,ary[p4]*7);36         if(ary[i] == ary[p1]*2)37             p1 ++;38         if(ary[i] == ary[p2]*3)39             p2 ++;40         if(ary[i] == ary[p3]*5)41             p3 ++;42         if(ary[i] == ary[p4]*7)43             p4 ++;44     }45     while(~scanf("%d",&n) && n)46     {47         printf("The %d",n);48         if(n % 10 == 1 && n % 100 != 11)49             printf("st ");50         else if(n % 10 == 2 && n % 100 != 12)51             printf("nd ");52         else if(n % 10 == 3 && n % 100 != 13)53             printf("rd ");54         else55             printf("th ");56         printf("humble number is %d.\n",ary[n]);57     }58     return 0;59 }