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 .
思路:
输出最后要加一个换行符!用stl中的优先队列实现小根堆。每次取出最小的一个,将它的2、3、5倍放入堆中,注意重复。
代码:
#include <bits/stdc++.h>
using namespace std;
//小根堆实现
//重载运算符
struct stt{
long long k;
};
bool operator < (stt a,stt b){
return a.k > b.k;
}
int main() {
int num=0;
stt cur;
cur.k=1;
priority_queue<stt> q;
q.push(cur);
while(1){
stt a,b,c;
stt ans=q.top();
q.pop();
num++;
//cout<<num<<' '<<ans.k<<endl;
if(num==1500) {
cout<<"The 1500'th ugly number is "<<ans.k<<'.'<<endl;
break;
}
a.k=2*ans.k;
b.k=3*ans.k;
c.k=5*ans.k;
if((a.k%5)&&(a.k%3)){ //含3或5因子一定在之前出现
q.push(a);
}
if(b.k%5){
q.push(b);
}
q.push(c);
}
return 0;
}