Project Euler task 44
Pentagonal numbers are generated by the formula, Pn=n(3n1)/2. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference is pentagonal and D = |Pk Pj| is minimised; what is the value of D?
-----------------------------------------------------------------------
#include < iostream >
#include < set >
using namespace std;
const int ciMax = 10000000;
int main() {
set< unsigned long > vPenths;
int i = 1;
while (1) {
unsigned long nTemp = i * (3 * i - 1) / 2;
if (nTemp > 10000000)
break;
vPenths.insert(nTemp);
i++;
}
for (set< unsigned long >::iterator it1 = vPenths.begin(); it1 != vPenths.end(); it1++)
for (set< unsigned long >::iterator it2 = it1; it2 != vPenths.end(); it2++) {
if (it1 == it2)
continue;
if (vPenths.find(*it2 - *it1) != vPenths.end() &&
vPenths.find(*it2 + *it1) != vPenths.end()) {
cout << *it1 << "-" << *it2 << "=" << *it2 - *it1 << endl;
break;
}
}
return 0;
}
Comments