1. 程式人生 > >計算第1500個醜數

計算第1500個醜數

//從小到大第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