uva136 Ugly numbers

Background

Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence

1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...

shows the first 11 ugly numbers. By convention, 1 is included.

Write a program to find and print the 1500'th ugly number.

Input and Output

There is noinput to this program. Output should consist of a single line asshown below, with <number> replaced by the number computed.

Sample output

The 1500'th ugly number is <number>.

思路

题目内容不多,就不嫌丑翻译了。都说翻译要信达雅,信、达还是有的,雅嘛就仁者见仁智者见智咯:-D。丑数定义为:一个自然数n,它的质数因子来自且只能来自集合{2, 3, 5}。由此可以给出丑数的定义公式,丑数ugly = 2^x + 3^y + 5^z,x\y\z都是自然数。然后就挨着找丑数,直到第1500个丑数也就是859963392(8亿多)。这样的线性判断、查找一直到859963392,我的电脑用时42秒。当然这样是会超时的,但可以先求出结果,再提交直接打印结果的代码也能Accepted。当然这是取巧,这种求解的方法不是有效的方法,但至少目前能Accepted,之后再图高效的方法。

值得一提的是,虽然计算结果是正确的,但是提交之后得到了wrong answer。之后又修改了好几次代码,还是wrong answer。直到我发现了一个细节——with <number> replaced by the number computed。注意,是替代<number>,而我一直都是替换的number,将两个多余的尖括号也输出了。记得下次,细嗅蔷薇:-D。

代码

#include <cstdio>
#include <ctime>
//#define yydebug

// 判断一个数是否是丑数
bool isUglyNumber(const unsigned int x);

int main(int argc, char **argv)
{
#ifdef yydebug
	freopen("out.txt", "w", stdout);
#endif
	//6之前已有5个丑数现在从6开始找寻第6个丑数
	int xTh = 5;
	for (unsigned int i = 6; ; i++)
	{
		if (isUglyNumber(i))
			xTh++;
		if (1500 == xTh)
		{
			printf("The 1500'th ugly number is %d.\n", i);
			break;
		}
	}
	return 0;
}

// 判断一个数是否是丑数
bool isUglyNumber(const unsigned int x)
{
	unsigned int tmp = x;
	while (true)
	{
		if (tmp % 2 != 0)
			break;
		tmp /= 2;
		if (1 == tmp)
			return true;
	}
	while (true)
	{
		if (tmp % 3 != 0)
			break;
		tmp /= 3;
		if (1 == tmp)
			return true;
	}
	while (true)
	{
		if (tmp % 5 != 0)
			break;
		tmp /= 5;
		if (1 == tmp)
			return true;
	}
	return false;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值