/*************************************************************************
> File Name: 32_UglyNumber.c
> Author: Juntaran
> Mail: [email protected]
> Created Time: 2016年09月02日 星期五 12时29分59秒
************************************************************************/ #include <stdio.h>
#include <malloc.h> int isUgly(int number)
{
while (number % == )
number /= ;
while (number % == )
number /= ;
while (number % == )
number /= ; return (number==) ? : -;
} // 低效方法
int getUglyNumber1(int n)
{
if (n <= )
return -; int number = ;
while (n != )
{
++ number;
if (isUgly(number) == )
n --;
}
printf("%d\n", number);
return number;
} int MinOfThree(int a, int b, int c)
{
int minNum = a>b ? b : a;
minNum = minNum>c ? c : minNum;
return minNum;
} // 高效方法 空间换时间
int getUglyNumber2(int index)
{
if (index <= )
return index; int* ugly = (int*)malloc(sizeof(int) * index);
int i2 = ;
int i3 = ;
int i5 = ;
ugly[] = ; for (int i = ; i < index; ++i)
{
int temp2 = ugly[i2] * ;
int temp3 = ugly[i3] * ;
int temp5 = ugly[i5] * ; int minNum = MinOfThree(temp2, temp3, temp5);
ugly[i] = minNum; if (minNum == temp2)
i2 ++;
if (minNum == temp3)
i3 ++;
if (minNum == temp5)
i5 ++;
}
printf("%d\n", ugly[index - ]);
return ugly[index - ];
} int main()
{
getUglyNumber1();
getUglyNumber2();
}