zoukankan      html  css  js  c++  java
  • 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
    ",a[n-1]);
    	scanf("%d",&n);
    	}
    	return 0;
    }
    
  • 相关阅读:
    BootStrap详解之(一)
    Centos6.5安装与配置Tomcat-8的方法
    Centos下安装jdk详解
    Html基础详解之(jquery)之二
    四层和七层负载均衡的区别
    linux下用script和scriptreplay对命令行操作录像
    Linux批量部署工具Expect
    Linux日常之Ubuntu系统中sendmail的安装、配置、发送邮件
    Linux日常之定时向文件传内容
    Linux日常之以当前时间命名文件
  • 原文地址:https://www.cnblogs.com/cnsec/p/11830692.html
Copyright © 2011-2022 走看看