# Pentagonal Numbers

C++. This is the Problem 44 from Project Euler.

Question: Pentagonal numbers are generated by the formula, Pn=n(3n−1)/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 are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? Link to the page.

Solution: My approach is to increment the sum value in order to create a pentagonal numbers domain so that we can track those two numbers. I call them P1 and P2 for easy track where P2 > P1. While sum (P2+P1) increases by n going to infinity, the algorithm paces P1 from the start of the domain to the edge of the first half of the domain since P1 is always less than P2. Thus, P2 becomes observable by sum – P1. Then, the algorithm checks if P2 is pentagonal or not by quadratic equation formula. If yes, it checks the difference between P2 and P1 next. If the difference is pentagonal as well, it becomes the first hit and the minimised difference. Its running time is less than a second.

Answer is 5482660 where P1 = 1560090 and P2 = 7042750.