136 - Ugly Numbers

来源:互联网 发布:怎么跟网络管理员联系 编辑:程序博客网 时间:2024/05/17 04:41

Ugly numbers are numbers whose only primefactors are 2, 3 or 5. The sequence

1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...

shows the first 11 ugly numbers. Byconvention, 1 is included.

Write a program to find and print the 1500'thugly number.

Input and Output

There is no input to this program. Outputshould consist of a single line as shown below, with <number> replaced bythe number computed.

Sample output

The 1500'th ugly number is <number>.

代码:

#include<iostream>

#include<vector>

#include<queue>

#include<set>

using namespacestd;

typedef long longLL;//数据较大

int num[]={2,3,5};//允许的素数

 

int main()

{

priority_queue<LL,vector<LL>,greater<LL>  > pq;//别将>写在一起

//最小的元素排在最前面,存取生成的丑数

    set<LL> s;//存取所有生成的丑数,主要用来查找某一个丑数是否已经生成过

    pq.push(1);

    s.insert(1);

    for(int i=1;;i++)

    {

        LL x=pq.top();//最小的丑数

        pq.pop();

        if(i==1500)//当第1500次取最小的丑数时,取的就是第1500个丑数

        {

            cout<<"The 1500'th uglynumber is "<<x<<".\n";

            break;

        }

        for(int j=0;j<3;j++)

        {

            LL x2=x*num[j];//用最小的丑数生成新的丑数

            if(!s.count(x2))//若生成的丑数是新的

            {

                s.insert(x2);

                pq.push(x2);

            }

        }

    }

}

解析:

思路是每一次用最小的丑数分别*2,*3,*5,生成丑数,set中存放所有的已生成的丑数,在set中查找每一个生成的丑数,找到不再插入,找不到插入.(set非常适合于查找.线性时间)

859963392

0 0
原创粉丝点击