1525 Ugly Numbers[C]

1525 Ugly Numbers

时间限制:1000MS  内存限制:10000K
提交次数:0 通过次数:0

题型: 外判编程题   语言: C++

Description

Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...
shows the first 10 ugly numbers. By convention, 1 is included.
Given the integer n,write a program to find and print the n'th ugly number.



输入格式

Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.


输出格式

For each line, output the n’th ugly number .:Don’t deal with the line with n=0.


输入样例

1
2
9
0


输出样例

1
2
10


提示



来源

New Zealand 1990 Division I

作者

admin


思路:该题的关键在于如何快速求Ugly Number,Ugly Number是能被2,3,5整除的数,包括特殊的1。这里用到3个数初始值为0的m2、m3、m5,初始值1为a[0],a[1]=min(2*a[m2],3*a[m3],5*a[m5]),并使最小的2*a[m2]中的m2自加1,同理求得a[2]、a[3]等等。特别注意,2*a[m2]和3*a[m3]相等时,m2、m3都要加1。


代码:


#include <stdio.h>

int main()
{
    int i=1,m2=0,m3=0,m5=0,a[1500],n;
    a[0]=1;

    for(;i<1500;i++)
    {
        a[i]=a[m2]*2;
        if(a[i]>a[m3]*3)
        {
            a[i]=a[m3]*3;
        }
        if(a[i]>a[m5]*5)
        {
            a[i]=a[m5]*5;
        }
        if(a[i]==a[m2]*2)//如果有相同的则都加1
            m2++;
        if(a[i]==a[m3]*3)
            m3++;
        if(a[i]==a[m5]*5)
            m5++;
    }

//    for(i=0;i<1500;i++)
//        printf("%d ",a[i]);

    while(1)
    {
        scanf("%d",&n);
        if(n==0)
        {
            break;
        }
        else
        {
            printf("%d\n",a[n-1]);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值