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

Project Euler:Problem 45 Triangular, pentagonal, and hexagonal

2015-06-05 15:28 429 查看
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
TriangleTn=n(n+1)/21, 3, 6, 10, 15, ...
PentagonalPn=n(3n−1)/21, 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.

真是哔了狗了 没注意到int类型的数转换成long long类型的数,结果一直不对。。

#include <iostream>
#include <map>
using namespace std;

int main()
{
	map<unsigned long long, int>mp;
	for (unsigned long long i = 143; i <= 100000; i++)
	{
		unsigned long long a = i*(i + 1) / 2;
		mp[a]++;
		a = i*(3 * i - 1) / 2;
		mp[a]++;
		a = i*(2 * i - 1);
		mp[a]++;
	}
	int diff = numeric_limits<int>::max();
	int res = 0;
	map<unsigned long long, int>::iterator iter;
	for (iter = mp.begin(); iter != mp.end(); iter++)
	{
		if (iter->first > 40755)
		{
			if (mp[iter->first] == 3)
			{
				if (iter->first - 40755 < diff)
				{
					diff = iter->first - 40755;
					res = iter->first;
				}
			}
		}
	}
	cout << res << endl;
	system("pause");

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