136:Ugly Numbers

Ugly Numbers


Generate various ugly numbers from small to large, the smallest ugly number is 1, and for any ugly number x, 2x, 3x and 5x are also ugly numbers. In this way, a priority queue can be used to store all the generated ugly numbers, and each time the smallest ugly number is taken out, 3 new ugly numbers are generated. The only thing to note is that there are
multiple ways , so you need to determine whether an ugly number has been generated.

#include<iostream>
#include<vector>
#include<set>
#include<queue>
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);
    for(int i = 1;;i++){
        ll x = pq.top();pq.pop();
        if(i == 1500){
            cout<<"The 1500'th ugly number is "<<x<<".\n";
            break;
        }
        for(int j = 0;j < 3;j++){
            ll x2 = x*coeff[j];
            if(!s.count(x2)){ pq.push(x2); s.insert(x2); }
        }
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324524678&siteId=291194637