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.
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
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.
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
分析:
这个题的关键是模拟出来规律,然后用筛法离线求出1500个丑数。
一开始用了一种比较慢的算法模拟了一下
代码如下
//第一时间想到的低效算法
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int ans[1505];
const int tt[3]={2,3,5};
bool ugly(int x)
{
while(x!=1)
{
if(0==x%2)
x/=2;
else if(0==x%3)
x/=3;
else if(0==x%5)
x/=5;
else
return false;
}
return true;
}
int main()
{
int n,i,k;
k=0;
ans[k]=1;
for(i=2;k<1500;i++)
{
if(ugly(i))
ans[++k]=i;
}
while(cin>>n, n>0)
{
cout<<ans[n-1]<<endl;
}
return 0;
}
之后用筛法模拟出1500个丑数AC的
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int ans[1505];
int main()
{
int n,i,j,k,t;
memset(ans,0,sizeof(ans));
ans[1]=1;
i=1,j=1,k=1;
for(t=2; t<=1500; t++)
{
ans[t]=min(min(ans[i]*2,ans[j]*3),ans[k]*5);
if(ans[i]*2==ans[t])
++i;
if(ans[j]*3==ans[t])
++j;
if(ans[k]*5==ans[t])
++k;
}
while(cin>>n, n>0)
cout<<ans[n]<<endl;
return 0;
}