Home Project Euler Teaching Projects Gallery

Problem 45: Triangular, pentagonal, 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.


Algorthim:

We have formulas for triangle, pentagonal, and hexagonal. How do we check if a number belongs to actuallyt

Given a number, lets say x, it must satistify: $$ \frac{(n)(n + 1)}{2} = x$$ $$ \frac{(n)(3n - 1)}{2} = x$$ $$ \frac{(n)(2n - 1)}{2} = x$$ Each n value that each equation gives us can't bee the same. Also, but the main criteria is that they must be positive integers.

So, we can perform quadratic equation on each of the equations to get:

We go through the store[] divisors. If we don't get our condition, we break. If we do we raise our \(k\) value by 1. If at the end of the loop our k = 7, then it's a sub-string divible number! $$ n^2 + n - 2x -> \frac{-1 \pm \sqrt{1 + 8x}}{2} $$ So for this example, we see that 1 + 8x has to be a perfect square. Also, -1 + of this perfect square must be divisible by 2. We dont' take the negative solution since that yields a negative integer. So we check what x makes the determinant a perfect square AND -1 + of this square root of perfect square divisble by 2. We can apply this method for each the equations above and check for these conditions!

Code:

Result:

Answer: 1533776805
Runtime: 48.6 ms