G - Ugly Numbers

题目

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, 15, …
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find and print the 1500’th ugly number.

Input
There is no input to this program.

Output
Output should consist of a single line as shown below, with ‘’ replaced by the number
computed.

Sample Output
The 1500’th ugly number is .

题意

只要是把一个数分解,质因子只含有2,3,5的数,就为丑数。

解析

1.算法:我们知道一个较大的数可以分成两个质因子相乘,其中的质因子可能还可以分··· ···,所以我们倒推,以2,3,5为基数,这三个数任意若干次相乘构成的数是丑数也可以是构成丑数的质因子。

代码

#include<stdio.h>
int main()
{
    long long u[1501];//定义数组,这个数组是储存丑数。
    int i=1, j=1, k=1;
    int a, b, c;
    int mi;
    int n;
    u[i]=1;            //第一个丑数是1.

    for(n=2; n<1501; n++)//得出丑数,直到1500个。
    {
        a=2*u[i];      //以得到的丑数u[序号]乘以2,3,5这样的基数得到的还是丑数。
        b=3*u[j];
        c=5*u[k];

        mi=a;          //将丑数从小到大排序。
        if(mi>b)
            mi=b
        if(mi>c)
            mi=c;

        u[n]=mi;       //将a,b,c小的那个给本轮的u[n].
        if(a==u[n]) i++;//判断最小的那个丑数在a,b,c,哪一个中,是的话,相应计数器+1,即下一轮a或者b或者c乘以丑数,成为新的质因子。
        if(b==u[n]) j++;
        if(c==u[n]) k++;
    }

    printf("The 1500'th ugly number is %d.\n",u[1500]);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值