码迷,mamicode.com
首页 > 其他好文 > 详细

丑数(摘)

时间:2016-03-06 12:48:54      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

 

丑数是指不能被2,3,5以外的其他素数整除的数,把丑数从小到大排列起来,结果如下:

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

求第n个丑数

输入n

#include<iostream>
#include<queue>
#include<vector>
#include<set>
using namespace std;
typedef long long LL;
const int coeff[3]={2,3,5};
int main() 
{
    priority_queue<LL,vector<LL>,greater<LL> >pq;
    set<LL>s;
    pq.push(1);
    s.insert(1);
    int n;
    cin>>n;
    for(int i=1;;i++){
        LL x=pq.top();
        pq.pop();
        if(i==n){
            cout<<"The "<<n<<"‘th ugly number is "<<x<<".\n";
            break;
        }
        for(int j=0;j<3;j++){
            LL x2=x * coeff[j];
            if(!s.count(x2)){             //计数x2,不为0则存入队列中
                s.insert(x2);
                pq.push(x2);
            }
        }
    }
    system("pause");
    return 0;
}

因为queue仅为FIFO结构,不能说为一个容器,无count函数,所以用set存储来计数看是否有重复元素

 

丑数(摘)

标签:

原文地址:http://www.cnblogs.com/farewell-farewell/p/5245763.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!