Problem 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.
C++ source code
#include <iostream>
#include <map>
#include <iterator>
#include <cmath>
using namespace std;
typedef unsigned long long ULL;
class PE0045
{
private:
bool findNextTriangleNumber(ULL n, ULL max_n, ULL& number);
void printTriangleNumber(ULL number);
public:
void getNextTriangleNumber();
};
void PE0045::printTriangleNumber(ULL number)
{
ULL n;
n = (ULL)((sqrt((double long)(1 + number*8)) - 1)/2.0);
cout << "T(" << n << ") = ";
n = (ULL)((sqrt((double long)(1 + number*24)) + 1)/6.0);
cout << "P(" << n << ") = ";
n = (ULL)((sqrt((double long)(1 + number*8)) + 1)/4.0);
cout << "H(" << n << ") = " << number << endl;
cout << number << " is triangle number that is also pentagonal and hexagonal." << endl;
}
bool PE0045::findNextTriangleNumber(ULL n, ULL max_n, ULL& number)
{
map<ULL, int> TnPnHn_mp;
ULL Tn, Pn, Hn;
for (ULL i = n; i<max_n; i++)
{
Tn = i*(i + 1) / 2;
TnPnHn_mp[Tn]++;
Pn = i*(3 * i - 1) / 2;
TnPnHn_mp[Pn]++;
Hn = i*(2 * i - 1);
TnPnHn_mp[Hn]++;
}
map<ULL, int>::iterator iter;
for (iter = TnPnHn_mp.begin(); iter != TnPnHn_mp.end(); iter++)
{
if (3 == TnPnHn_mp[iter->first] && iter->first > 40755)
{
number = iter->first;
return true;
}
}
return false;
}
void PE0045::getNextTriangleNumber()
{
ULL n = 143, max_n = 50000;
bool found = false;
ULL number = 0;
while(false == found)
{
found = findNextTriangleNumber(n, max_n, number);
max_n += 50000;
}
printTriangleNumber(number);
}
int main()
{
PE0045 pe0045;
pe0045.getNextTriangleNumber();
return 0;
}
Python source code
import math
def findNextTriangleNumber(max_n):
TnPnHn_dict = {}
for n in range(1, max_n+1):
Tn = int(n*(n + 1)/2.0)
if Tn not in TnPnHn_dict.keys():
TnPnHn_dict[Tn] = 1
else:
TnPnHn_dict[Tn] += 1
Pn = int(n*(3*n - 1)/2.0)
if Pn not in TnPnHn_dict.keys():
TnPnHn_dict[Pn] = 1
else:
TnPnHn_dict[Pn] += 1
Hn = n*(2*n - 1)
if Hn not in TnPnHn_dict.keys():
TnPnHn_dict[Hn] = 1
else:
TnPnHn_dict[Hn] += 1
for key, value in TnPnHn_dict.items():
if 3 == value and key > 40755:
return key
return 0
def printTriangleNumber(number):
n = int((math.sqrt(1+number*8)-1)/2.0)
print('T(%d) = '%n,end='')
n = int((math.sqrt(1+number*24)+1)/6.0)
print('P(%d) = '%n,end='')
n = int((math.sqrt(1+number*8)+1)/4.0)
print('H(%d) ='%n,number)
print(number,"is triangle number that is also pentagonal and hexagonal.")
def getNextTriangleNumber():
max_n, number = 50000, 0
while 0 == number:
number = findNextTriangleNumber(max_n)
max_n += 50000
printTriangleNumber(number)
def main():
getNextTriangleNumber()
if __name__ == '__main__':
main()