ugly number(丑数)

今天来了一哥们面试,我们老大让他写下面的程序,这哥们挺牛的,5分钟就写好了,NB,老大灰常满意:

其实这是考查对动态规划的理解。

题目:把只包含因子235的数称作丑数(Ugly Number)。例如68都是丑数,但14不是,因为它包含因子7。习惯上我们把1当做是第一个丑数。求出第n个丑数。

/**
*******************************************************************************
*   
*   @frief    	find the ugly number
*   @version	$1.0$
*   @date	    $2012.9.12$
*   @author     $Alfred Wang$
*
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>

/**
*******************************************************************************
*   
*   @brief    	find the min number
*   @param	    num1: Input; the number waiting for comparing
*   @param	    num2: Input; the number waiting for comparing
*   @param	    num3: Input; the number waiting for comparing
*   @param      return: Output; return the min number
*
*******************************************************************************/
int MinNumber(int num1, int num2, int num3)
{
    int temp;
	temp = (num1 < num2 ? num1 : num2);
	temp = (temp < num3 ? temp : num3);
	return temp;
}

/**
*******************************************************************************
*   
*   @brief    	find the Nth ugly number
*   @param	    n: Input; the index
*   @param      return: Output; return the Nth ugly number
*
*******************************************************************************/

long UglyNumber(int n)
{
	assert(n > 0);
	long temp;
	int itor;
	int itor2 = 0;
	int itor3 = 0;
	int itor5 = 0;
	int *Ptr = (int *)malloc(n * sizeof(int));
	assert(Ptr != NULL);
	*Ptr = 1;
	for( itor = 1; itor < n; itor++)
	{
		temp = MinNumber(*(Ptr + itor2) * 2, *(Ptr + itor3) * 3, 
		                *(Ptr + itor5) *5);
		if(temp == *(Ptr + itor2) * 2)
		{
			itor2++;
		}
		if(temp == *(Ptr + itor3) * 3)
		{
			itor3++;
		}
		if(temp == *(Ptr + itor5) * 5)
		{
			itor5++;
		}
		*(Ptr + itor) = temp;
	}
	temp = *(Ptr + n - 1);
	free(Ptr);
	return temp;
}

int main(void)
{
	long uglyNum;
	int n;
	printf("input the number n: ");
	scanf("%d", &n);
	uglyNum = UglyNumber(n);
	printf("the nth ugly number is %ld\n", uglyNum);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值