B

来源:互联网 发布:程序员经典面试题目 编辑:程序博客网 时间:2024/04/30 03:16
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. 
Sample Input
1234111213212223100100058420
Sample Output
The 1st humble number is 1.The 2nd humble number is 2.The 3rd humble number is 3.The 4th humble number is 4.The 11th humble number is 12.The 12th humble number is 14.The 13th humble number is 15.The 21st humble number is 28.The 22nd humble number is 30.The 23rd humble number is 32.The 100th humble number is 450.The 1000th humble number is 385875.The 5842nd humble number is 2000000000.
题意分析:此题的意思就是从1开始,质因子只有2,3,5,7的数字,但是1也是,1,2,3,4,5,6,7,8等等,然后让你求解第n个数是多少。这道题我做的时候就是打表。就是先在输入之前把所有humble number的值给算出来,然后最后输入n,就对应表中的n。
这道题还有一个点就是你要输出什么1st,2nd,3rd,4-9th,我当时做的时候就没注意导致错误。判断条件是n%10==1&&n%100!=11,输出"st",,,,n%10==2&&n%100!=12,输出
"nd",,,,,,n%10==3&&n%100!=13,输出"rd"(其实就是英文单词的第几个)只要注意了这两个点,即打表和英文单词的第几,基本上就可以AC了。
代码实现:
#include<bits/stdc++.h>using namespace std;const int maxn=5880;//题意上n最多取5842,我可以取多一点。long long int hunger[maxn];//用long long int 我觉得比较保险,,不会超范围,也可以用int;void running()//对数据进行预处理{    int i;    int a,b,c,d;    hunger[1]=1;//第一个数为1;    int s1=1,s2=1,s3=1,s4=1;//s1,s2,s3,s4用来记录你乘了多少次2,3,5,7;    int z1,z2,z3,z4;//用于保存你的乘积    for(i=2;i<=maxn;i++)//从第二个开始保存    {        z1=hunger[s1]*2;//乘2;//第一次z1=2//第二次z1=4//第三次z1=4        z2=hunger[s2]*3;//乘3;//第一次z2=3//第二次z2=3//第三次z2=7        z3=hunger[s3]*5;//乘5;//第一次z3=5//第二次z3=5//第三次z3=5        z4=hunger[s4]*7;//乘7; //第一次z4=7//第二次z4=7//第三次z4=7        hunger[i]=min(min(z1,z2),min(z3,z4));//然后判断哪个最小,最小的放在数组里面去;//所以说依次就把2,3,4,5等等数据存进去了;       //如果已经乘了一次了,则下一次就应该是用再乘一次的去判断,其他则不变。       if(hunger[i]==z1)           s1++;       if(hunger[i]==z2)           s2++;       if(hunger[i]==z3)           s3++;       if(hunger[i]==z4)           s4++;    }}int main(){    running();//进行预处理    int n;    while(scanf("%d",&n)!=EOF)    {        if(n==0)//输入为0,退出输入:            break;        else//判断第几用哪个英文;        {if(n%10==1&&n%100!=11)            printf("The %dst humble number is ",n);        else if(n%10==2&&n%100!=12)            printf("The %dnd humble number is ",n);        else if(n%10==3&&n%100!=13)            printf("The %drd humble number is ",n);        else            printf("The %dth humble number is ",n);        printf("%lld.\n",hunger[n]);//直接输出n对应的值,因为我的humber[]是全局变量。        }    }    return 0;}


原创粉丝点击