题目大意
思路分析
丑陋的数字是只有2、3或5是质因数的数字。序列1、2、3、4、5、6、8、9、10、12、…显示前10个难看的数字。按照惯例,包含1。给定整数n,编写一个程序来查找并打印第n个丑陋的数字。
思路分析
拿到题首先想到埃及筛法,先筛出所以质因数,然后
//对于所有包含非2,3,5素数因子的打上标签
for (int i = 7; i < MAX; i++) {
if (isPrime[i])
for (int j = i; j < MAX; j += i)isUgly[j] = 0;
}
然后完结撒花个鬼 ,要有1500各ugly的数字,需要有不少于200000000的数组来筛,显然我们没有这么大的数组,那么就剩下两个办法,打表or找规律,打表很快,ctrl+c,ctrl+v,printf
over,但是还是找规律来的心里安稳
其实题目中说得很清楚了,质因数只有2,3,5,那么我们的序列
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...
其实就是每次找一个序列中的最小值,然后给他*2,*3,*5,如果得到的结果没有在集合中,那么就把他加进去。
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string>
#include<string.h>
#include<map>
#include<queue>
#include<cstdio>
using namespace std;
#define ll long long
#define MAX 1505
vector<ll> res;
ll n;
int main() {
priority_queue<ll, vector<ll>, greater<ll> > q;
q.push(1);
while (res.size() < 1500) {
ll v = q.top(); q.pop();
ll in = lower_bound(res.begin(), res.end(), v) - res.begin();
if (in == res.size() || res[in] != v) {
res.push_back(v);
q.push(v * 2);
q.push(v * 3);
q.push(v * 5);
}
}
while (cin >> n && n)
cout << res[n - 1] << endl;
}