Ugly Numbers
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.
#include<iostream>
using namespace std;
long long heap[5000000];
long long ualy[2000];
void swap(long long &a,long long &b);
void put(int &len,long long num);
long long get(int &len);
int main()
{
heap[1]=1;
int len=1;
long long n,num,pre=0;
int i;
for(i=1;i<=1500;)
{
num=get(len);
if(pre!=num)
{
ualy[i++]=num;
pre=num;
put(len,2*num);
put(len,3*num);
put(len,5*num);
}
}
while(cin>>n&&n)
{
cout<<ualy[n]<<endl;
}
return 0;
}
void swap(long long &a,long long &b)
{
long long temp;
temp=a;
a=b;
b=temp;
}
void put(int &len,long long num)
{
len++;
heap[len]=num;
int son=len;
while(son!=1&&heap[son]<heap[son/2])
{
swap(heap[son],heap[son/2]);
son/=2;
}
}
long long get(int &len)
{
long long min=heap[1];
heap[1]=heap[len];
--len;
int son=1;
while(son*2<=len)
{
if(son*2+1>len||heap[son*2]<heap[son*2+1])
son=son*2;
else
son=son*2+1;
if(heap[son/2]>heap[son])
swap(heap[son],heap[son/2]);
else
break;
}
return min;
}
using namespace std;
long long heap[5000000];
long long ualy[2000];
void swap(long long &a,long long &b);
void put(int &len,long long num);
long long get(int &len);
int main()
{
heap[1]=1;
int len=1;
long long n,num,pre=0;
int i;
for(i=1;i<=1500;)
{
num=get(len);
if(pre!=num)
{
ualy[i++]=num;
pre=num;
put(len,2*num);
put(len,3*num);
put(len,5*num);
}
}
while(cin>>n&&n)
{
cout<<ualy[n]<<endl;
}
return 0;
}
void swap(long long &a,long long &b)
{
long long temp;
temp=a;
a=b;
b=temp;
}
void put(int &len,long long num)
{
len++;
heap[len]=num;
int son=len;
while(son!=1&&heap[son]<heap[son/2])
{
swap(heap[son],heap[son/2]);
son/=2;
}
}
long long get(int &len)
{
long long min=heap[1];
heap[1]=heap[len];
--len;
int son=1;
while(son*2<=len)
{
if(son*2+1>len||heap[son*2]<heap[son*2+1])
son=son*2;
else
son=son*2+1;
if(heap[son/2]>heap[son])
swap(heap[son],heap[son/2]);
else
break;
}
return min;
}