UVA - 136 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
There is no input to this program.
Output
Output should consist of a single line as shown below, with ‘’ replaced by the number
computed.
Sample Output
The 1500’th ugly number is .
就是找到第1500个ugly number:如果有质因子,那么只能是2 3 5的数
思路:最小的ugly number是1。如果这个数是ugly number,比如a,那么2*a、3*a、5*a都是ugly number,把这些数放进优先队列中,第1500出来的数就是要找的数。但是注意,如果对这个a*2或者*3之后可以也是3、5或者5的倍数,说明这个数已经列举过了
所以,这道题就是SLT+模拟(把数都模拟一遍)
#include <iostream>
#include <queue>
using namespace std;
int main(){
long long t,a, b, c;
priority_queue<long long, vector<long long>, greater<long long> > q;
q.push(1);
long long n = 0;
for(int i = 1; i < 1510; i++){
t = q.top();
q.pop();
n++;
if(n == 1500)
printf("The 1500'th ugly number is %d.\n", t);
a = t * 2;
b = t * 3;
c = t * 5;
if((a % 5) && (a % 3))
q.push(a);
if((b % 5))
q.push(b);
q.push(c);
}
return 0;
}