您的位置:首页 > 编程语言 > Go语言

Project Euler 题解 #45 Triangular, pentagonal, and hexagonal

2013-10-29 11:04 302 查看

题目:Triangular, pentagonal, and hexagonal

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:

TriangleTn=n(n+1)/21, 3, 6, 10, 15, ...
PentagonalPn=n(3n

1)/2
1, 5, 12, 22, 35, ...
HexagonalHn=n(2n

1)
1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.

Find the next triangle number that is also pentagonal and hexagonal.

分析

经计算可得出以下判定方法:

1.一个数X为三角数,等价于

为整数,n表示X的下标。

2.一个数X为五边形数,等价于

为整数,n表示X的下标。

3.一个数X为六边形数,等价于

为整数,n表示X的下标。

那么可以用来解该题,显然这种方法会很慢。

进一步观察,凡六边形数均为三角数,那么就不用判断三角数了。

若用判定条件来检验,由于存在开方或平方,效率会很低。



对五边形数来说,Pn-1-Pn = 3n+1。

对六边形数来说,Hn-1-Hn = 4n+1。

那么具体实现中,可以用加法代替开方。

代码实现

/http://projecteuler.net/problem=45
//Triangular, pentagonal, and hexagonal

#include <cmath>
#include <iostream>
#include <iomanip>
#include <limits>

int _tmain(int argc, _TCHAR* argv[])
{
	unsigned __int64 x = 1, y = 1;
	unsigned __int64 i = 1, j = 1;
	while (x < LLONG_MAX)
	{
		while (y < x)
		{
			y += 4 * j + 1;
			++j;
		}

		if (x == y)
		{
			cout<<"<"<<i<<","<<j<<"> = "<<std::setprecision(30)<<x<<endl;
		}
		x += (3 * i + 1);
		++i;
	}

	system("pause");
	return 0;
}

输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: