Project Euler 45: 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)/2 | 1, 5, 12, 22, 35, ... | ||
| Hexagonal | Hn=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.
这道题目的求解是按照下述方法进行的
如果一个数x是一个Triangle number,则(sqrt(8x+1)-1)/2为一个整数。
如果一个数x是一个pentagonal number,则(sqrt(24x+1)+1)/6是一个整数。
如果一个数x是一个hexagonal number,则(sqrt(8x+1)+1)/4是一个整数。
因此采用最暴力的办法便是从第144个hexagonal number开始不断地枚举并判断这个数是不是Triangle number和pentagonal number。但是进一步我们可以发现H(n)=T(2n-1)的,因此我们在判断的时候可以直接判断一个数同时是hexagonal number和pentagonal number即可。
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cassert>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <utility>
#include <numeric>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3fLL;
const double eps = 1e-8;
const double pi = acos(-1.0);
int main() {
for(int i = 144; ; ++i) {
long long t = i * (2 * i - 1);
double t1 = (sqrt(24 * t * 1.0 + 1.0) + 1) / 6.0;
long long t2 = (int)t1;
if(abs(t1 - t2) < eps) {
cout << t << endl;
break;
}
}
return 0;
}
posted on 2015-01-27 11:30 sponge_wxy 阅读(108) 评论(0) 收藏 举报
浙公网安备 33010602011771号