1525 Ugly Numbers
时间限制:1000MS 内存限制:10000K
提交次数:0 通过次数:0
题型: 外判编程题 语言: C++
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.
输入格式
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
输出格式
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
输入样例
1 2 9 0
输出样例
1 2 10
提示
来源
New Zealand 1990 Division I作者
admin
思路:该题的关键在于如何快速求Ugly Number,Ugly Number是能被2,3,5整除的数,包括特殊的1。这里用到3个数初始值为0的m2、m3、m5,初始值1为a[0],a[1]=min(2*a[m2],3*a[m3],5*a[m5]),并使最小的2*a[m2]中的m2自加1,同理求得a[2]、a[3]等等。特别注意,2*a[m2]和3*a[m3]相等时,m2、m3都要加1。
代码:
#include <stdio.h>
int main()
{
int i=1,m2=0,m3=0,m5=0,a[1500],n;
a[0]=1;
for(;i<1500;i++)
{
a[i]=a[m2]*2;
if(a[i]>a[m3]*3)
{
a[i]=a[m3]*3;
}
if(a[i]>a[m5]*5)
{
a[i]=a[m5]*5;
}
if(a[i]==a[m2]*2)//如果有相同的则都加1
m2++;
if(a[i]==a[m3]*3)
m3++;
if(a[i]==a[m5]*5)
m5++;
}
// for(i=0;i<1500;i++)
// printf("%d ",a[i]);
while(1)
{
scanf("%d",&n);
if(n==0)
{
break;
}
else
{
printf("%d\n",a[n-1]);
}
}
return 0;
}