今天来了一哥们面试,我们老大让他写下面的程序,这哥们挺牛的,5分钟就写好了,NB,老大灰常满意:
其实这是考查对动态规划的理解。
题目:把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但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;
}