Filename: prob45.cc
// Problem 45 // 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(3n1)/2 1, 5, 12, 22, 35, ... // Hexagonal Hn=n(2n1) 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. #include <iostream> #include <math.h> using namespace std; //inline bool isTriangle(const unsigned long long Tn) //{ // return ceil((-1 + sqrt(1+8*Tn))/2) == floor((-1 + sqrt(1+8*Tn))/2); //} inline bool isPentagonal(const unsigned long long Pn) { return ceil((1 + sqrt(1+24*Pn))/6) == floor((1 + sqrt(1+24*Pn))/6); } inline bool isHexagonal(const unsigned long long Hn) { return ceil((1 + sqrt(1+8*Hn))/4) == floor((1 + sqrt(1+8*Hn))/4); } inline unsigned long long T(const unsigned int n) { return n*(n+1)/2; } int main() { cout << T(285) << endl; for(unsigned int i=286; ; ++i) { if(isPentagonal(T(i)) && isHexagonal(T(i))) { cout << T(i) << endl; return 0; } } return 0; }
syntax highlighted by Code2HTML, v. 0.9.1
No comments:
Post a Comment