ugly number (丑数)

A - Ugly Numbers

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的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

分析

遍历一遍肯定是要超时的,我们很容易想到,所有的丑数都是由某一个丑数乘上2,3,5得来的,我们就可以由1开始得到所有的丑数。
我们选择用指针实现求丑数的过程,先令三个指针全部指向第一个数,从此开始,每次将p1,p2,p3分别乘2,3,5的最小值加入数组,并将求这个最小值对应的指针移到下一个可乘的位置。

代码

#include<stdio.h>
#include<math.h>
int min(int a,int b,int c)
{
	int t=a<b?a:b;
	return t<c?t:c;
}
int main()
{
	int a[1505],num=1,n,s;
	a[0]=1;
	int *p1=a;
	int *p2=a;
	int *p3=a;
	while(num<1503)
	{
		s=min(2*(*p1),3*(*p2),5*(*p3));
			 a[num]=s;//这里一定要先加入数组啊!!之前放到了下面三个循环的后面,导致错误。。
		 while(2*(*p1)<=s)              
			 ++p1;         
		 while(3*(*p2)<=s)              
			 ++p2;          
		 while(5*(*p3)<=s)              
			 ++p3;  
		 num++;
	}
	scanf("%d",&n);
	while(n!=0)
	{	printf("%d\n",a[n-1]);
	scanf("%d",&n);
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值