## Project Euler: Problem 45 – Triangular, pentagonal, and hexagonal

#### 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(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.

#### Idea:

Looking at the list of triangle and hexagonal numbers, I made an educated guess that all hexagonal numbers are triangle numbers, so that narrowed down the problem to “Find the next pentagonal number that is also hexagonal”.

From there I just generated the next hexagonal number (since it grows faster than pentagonal numbers), and started generating pentagonal numbers until they were no longer smaller than the hexagonal number. If it just so happened that the pentagonal number was equal to the hexagonal number, I found my answer.

```String answer = "";

BigInteger pent = new BigInteger("40755");
BigInteger hex = new BigInteger("40755");
int h = 143;
int p = 165;
boolean matches = false;

while(!matches) {
h++;
hex = BigInteger.valueOf(h).multiply(
BigInteger.valueOf(2).multiply(
BigInteger.valueOf(h)).subtract(BigInteger.ONE));
while(pent.compareTo(hex) < 0) {
p++;
pent = BigInteger.valueOf(p).multiply(
BigInteger.valueOf(3).multiply(
BigInteger.valueOf(p)).subtract(BigInteger.ONE))
.divide(BigInteger.valueOf(2));
}
if(pent.compareTo(hex) == 0) {
matches = true;
}
}