计算第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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值