Ugly Numbers
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 21920 | Accepted: 9789 |
Description
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, ...
shows the first 10 ugly numbers. By convention, 1 is included.
Given the integer n,write a program to find and print the n'th ugly number.
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...
shows the first 10 ugly numbers. By convention, 1 is included.
Given the integer n,write a program to find and print the n'th ugly number.
Input
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
Output
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
Sample Input
1
2
9
0
Sample Output
1
2
10
Source
New Zealand 1990 Division I,UVA 136
用set 自动去除重复元素的性质,也可以用一个优先队列保存所有已生成的丑数,每次取出最小的丑数,生产3个新的丑数,因为丑数有多种生成方式所以每次要判断一个丑数是否已经生成过了
set代码:
#include<cstdio>
#include<set>
#include<queue>
using namespace std;
#define ll long long
#define N 1510
set<ll> s;
set<ll> :: iterator it;
ll un[N];
int main()
{
int n, c = ;
s.clear();
s.insert();
it = s.begin();
while(c<)
{
ll u = *it;
un[c++] = u;
s.insert(*u), s.insert(*u), s.insert(*u);
it++;
}
// for(int i = 0; i < 20; i++) printf("%lld ", un[i]); puts("");
while(~scanf("%d",&n),n)
printf("%lld\n",un[n-]);
return ;
}
用到优先队列的方法:
#include<cstdio>
#include<set>
#include<queue>
using namespace std;
#define ll long long
#define N 1510
set<ll> s;
priority_queue<ll, vector<ll> ,greater<ll> > qu;
ll un[N];
int main()
{
int n;
s.insert();
qu.push();
for(int i = ; i < ; i++)
{
ll tm = qu.top();
if(!s.count(tm*)) { s.insert(tm*) ; qu.push(tm*);}
if(!s.count(tm*)) { s.insert(tm*) ; qu.push(tm*);}
if(!s.count(tm*)) { s.insert(tm*) ; qu.push(tm*);}
qu.pop();
}
set<ll>::iterator it;
int cnt = ;
for( it = s.begin() ; cnt < ; it++)//结束条件改一下 要是it<s.end() 会runtime error
{
un[cnt++] = (*it);
}
// for(int i = 0; i < 1501; i++) printf("%lld\n", un[i]);
while(~scanf("%d",&n),n) {
printf("%lld\n",un[n-]);
}
return ;
}
注意,结束条件是pop了1500次,不是s的size是1500,因为最后还会进来更小的值