练习三1004

来源:互联网 发布:进入福彩内部数据 编辑:程序博客网 时间:2024/05/04 18:40
Problem D
Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 16   Accepted Submission(s) : 8
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. <br><br>Write a program to find and print the nth element in this sequence<br>
 

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.<br>
 

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.<br>
 

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.
 

Statistic |Submit | Back

题意:

从1开始找出第n个只能被2,3,5,7整除的数,并按照n的英文表示方法输出;

思路:

这道题太恶心了。刚开始想从8开始,(i=1;i<n;i++) (j=2;j<n;j++) 找到a[i]*a[j]>a[n-1]的最小值赋给a[n],但超时。换了scanf,printf还不行,之后又看了dicuss中别人的代码,发现直接用2*a[i],3*a[i],5*a[i],7*a[i],中大于a[n-1]的最小的一个赋值给a[n]用时会大大减少,但rw。又仔细看了遍题发现本题的输出非常特别,英语不好,只好再看discuss,输出问题解决了,但又超时了,实在想不出更优化的方法了,又看了discuss,原来别人都是先把这5842个数求都出来之后再输入n,找到对应的a[n]输出,而我是先输入n求出a[n],再输入一个n再重新求a[n],这样确太耗时了。

代码:

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    int n;
    long long a[5844];
    a[1]=1;a[2]=2;a[3]=3;a[4]=4;a[5]=5;a[6]=6;a[7]=7;
    for(int i=8;i<=5842;i++)
            {
                long long tmp=2000000002;
                for(int j=2;j<i;j++)
                {
                    if(2*a[j]<tmp&&2*a[j]>a[i-1])
                    tmp=2*a[j];
                    if(3*a[j]<tmp&&3*a[j]>a[i-1])
                    tmp=3*a[j];
                    if(5*a[j]<tmp&&5*a[j]>a[i-1])
                    tmp=5*a[j];
                    if(7*a[j]<tmp&&7*a[j]>a[i-1])
                    tmp=7*a[j];
                }
                a[i]=tmp;
            }
    while(scanf("%d",&n))
    {
        if(n==0) break;
        if(n%10==1&&n%100!=11)
        printf("The %dst",n);
        else if(n%10==2&&n%100!=12)
        printf("The %dnd",n);
        else if(n%10==3&&n%100!=13)
        printf("The %drd",n);
        else printf("The %dth",n);
        printf(" humble number is %d.\n",a[n]);
    }
    return 0;
}







0 0
原创粉丝点击