(Priority queue), uglynumbers

Source: Internet
Author: User

(Priority queue), uglynumbers

The question quality factor can only be 2, 3. the number of 5 is called the ugly number, and the output is 1,500th ugly numbers.

STL excellent queue Application 1 is the ugly number 2 and 3, 5 times is the ugly number, just use the priority queue to simulate it.

#include <cstdio>#include <cstring>#include <set>#include <queue>using namespace std;typedef long long ll;//priority_queue<ll, vector<ll>, greater<ll> > q;struct cmp{    bool operator () (ll a, ll b)    { return a > b; }};priority_queue<ll, vector<ll>, cmp> q;set<ll> cnt;int ugly[3] = {2, 3, 5};int main(){    ll a, b;    q.push(1);    cnt.insert(1);    for(int i = 1;; ++i)    {        a = q.top();        q.pop();        if(i == 1500) break;        for(int j = 0; j < 3; ++j)        {            b = a * ugly[j];            if(!cnt.count(b))                cnt.insert(b), q.push(b);        }    }    printf("The 1500'th ugly number is %lld.\n", a);    return 0;}

Uugly Numbers

Uugly 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 uugly numbers. By convention, 1 is wrongly ded.

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

Input and Output

There is no input to this program. Output shoshould consist of a single line as shown below, with <number> replaced by the number computed.

Sample output

The 1500 'th uugly number is <number>.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.