UVa 136 - Ugly Numbers

 

 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 and Output

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

 

Sample output

The 1500'th ugly number is <number>.

 1 // UVa136 Ugly Numbers

 2 // Rujia Liu

 3 // 代码由刘汝佳提供,我是在我的水平下,加以注释,学习大神的思想

 4 #include<iostream>

 5 #include<vector>

 6 #include<queue>

 7 #include<set>

 8 using namespace std;

 9 typedef long long LL;

10 const int coeff[3] = {2, 3, 5};

11 

12 int main() {

13   priority_queue<LL, vector<LL>, greater<LL> > pq;//越小的整数(LL)优先级越大的优先队列

14   set<LL> s;

15   pq.push(1);

16   s.insert(1);

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

18     LL x = pq.top(); pq.pop();

19     if(i == 1500) {

20       cout << "The 1500'th ugly number is " << x << ".\n";

21       break;

22     }

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

24       LL x2 = x * coeff[j];

25       if(!s.count(x2)) { s.insert(x2); pq.push(x2); }

26     }

27   }

28   return 0;

29 }

 

你可能感兴趣的:(number)