//从小到大第1500个丑数
//方法1:
#include <stdio.h>
bool IsUgly(int num)
{
while(num%2 == 0)
num /= 2;
while(num%3 == 0)
num /= 3;
while(num%5 == 0)
num /= 5;
if(num == 1)
return true;
else
return false;
}
int GetUglyNumber(int index)
{
if(index <=0)
return 0;
int number = 1;
int UglyFound = 0;
while(UglyFound < index)
{
number ++;
if(IsUgly(number))
UglyFound ++;
}
return number;
}
int main()
{
printf("%d", GetUglyNumber(1500));
printf("\n");
return 0;
}
//output:860934420
//时间效率不高,因为在非丑数上也做用算了,如果只在丑数上做运算,势必会提高时间效率,但是需要牺牲空间效率,假设第一个丑数为2
//方法2:
#include <stdio.h>
int Min(int number1, int number2, int number3)
{
int min = number1;
if(min > number2)
min = number2;
if(min > number3)
min = number3;
return min;
}
int GetUglyNumber(int index)
{
if(index <= 0)
return 0;
int* pUglyNumbers = new int[index + 1];//需要牺牲空间效率
pUglyNumbers[0] = 1;
int nextUglyIndex = 1;
int* pMultiply2 = pUglyNumbers;
int* pMultiply3 = pUglyNumbers;
int* pMultiply5 = pUglyNumbers;
while(nextUglyIndex < index + 1)
{
int min = Min(*pMultiply2 * 2, *pMultiply3 * 3, *pMultiply5 * 5);
pUglyNumbers[nextUglyIndex] = min;
while(*pMultiply2 * 2 <= pUglyNumbers[nextUglyIndex])
++pMultiply2;
while(*pMultiply3 * 3 <= pUglyNumbers[nextUglyIndex])
++pMultiply3;
while(*pMultiply5 * 5 <= pUglyNumbers[nextUglyIndex])
++pMultiply5;
++nextUglyIndex;
}
int ugly = pUglyNumbers[nextUglyIndex - 1];
delete []pUglyNumbers;
return ugly;
}
int main()
{
printf("%d", GetUglyNumber(1500));
printf("\n");
return 0;
}
//output:860934420
计算第1500个丑数
最新推荐文章于 2020-07-10 15:32:08 发布