Project Euler task 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(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.

---------------------------------------------------------------------------

#include < iostream >
#include < math.h >

using namespace std;

int main() {
long int x = 0;

for (int y = 1; y < 1000000; y++) {
long double fx = sqrt((long double) 3 * y * y - 2);

if (fx - floor(fx) > 0)
continue;

x = floor(fx);

long double fn = (fx + 1) / 6;
if (fn - floor(fn) > 0)
continue;

long double fm = ((double) y + 1) / 4;
if (fm - floor(fm) > 0)
continue;

long long int n = (x + 1) / 6; // pentagonal

cout << n * (3 * n - 1) / 2 << " : " << x << " " << y << endl;
}

return 0;
}

Comments

Popular Posts