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>.
丑数是指不能被2,3,5以外的其他素数整除的数。把丑数从小到大排列起来,结果如下:
1,2,3,4,5,6,8,9,10,12,15,…
求第1500个丑数。
#include <cstdio>
#include <queue>
using namespace std;
const int maxNum = 1505;
int main() {
long long a, b, c;
// 优先队列
priority_queue<long long, vector<long long>, greater<long long> > pq;
// 初始化队列有1这个元素
pq.push(1);
// 计数
long long num = 0;
for(int i = 1; i < maxNum; i++) {
long long ans = pq.top();
// test
// printf("%d \t", ans);
pq.pop();
num++;
if(num == 1500) {
printf("The 1500'th ugly number is %d.\n", ans);
}
// 如果ans是ugly number,则2ans,3ans,5ans都是丑数
a = ans * 2;
b = ans * 3;
c = ans * 5;
// a 如果与 b或c是同一数的因数关系,那么该数一定在b或c中出现过
// 因为b或c比a大
if((a % 5) && (a % 3)) {
pq.push(a);
}
// 同理
if((b % 5)) {
pq.push(b);
}
pq.push(c);
}
return 0;
}