题目:Triangular, pentagonal, and hexagonal
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle | Tn=n(n+1)/2 | 1, 3, 6, 10, 15, ... | ||
Pentagonal | Pn=n(3n![]() | 1, 5, 12, 22, 35, ... | ||
Hexagonal | Hn=n(2n![]() | 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;
}
输出: