poj 1338 Ugly Numbers

Ugly Numbers
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 21649   Accepted: 9680

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
10

由题意可知这个数一定是2或3或5的倍数则每次取这三个数的倍数中最小的那个即可
注意:数据范围超过了int型 应该使用long long或者int_64
#include<stdio.h>
#include<string.h>
#define MAX 1510
#define min(x,y)(x<y?x:y)
long long ugly[MAX];
int main()
{
	int n,m,j,i;
	int a,b,c;
	int u2,u3,u5;
	u2=1;u3=1;u5=1;
	ugly[1]=1;
	for(i=2;i<MAX;i++)
	{
		a=2*ugly[u2];
		b=3*ugly[u3];
		c=5*ugly[u5];
		ugly[i]=min(a,min(b,c));
		if(ugly[i]==a) u2++;
		if(ugly[i]==b) u3++;
		if(ugly[i]==c) u5++;
	}
	while(scanf("%d",&n),n)
	{
		printf("%d\n",ugly[n]);
	}
	return 0;
} 

  

posted @ 2015-06-23 13:41  非我非非我  阅读(176)  评论(0编辑  收藏  举报