Tuesday, 18th August, 2009

Project Euler Problem 45

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle T_(n)=n(n+1)/2 1, 3, 6, 10, 15, …
Pentagonal P_(n)=n(3n−1)/2 1, 5, 12, 22, 35, …
Hexagonal H_(n)=n(2n−1) 1, 6, 15, 28, 45, …

It can be verified that T_(285) = P_(165) = H_(143) = 40755.

Find the next triangle number that is also pentagonal and hexagonal.

This took me a very long time to do it, I was trying to optimise it left right and centre, and using explicit loops and all sorts. Turns out what we need is Python 3.x with it’s set comprehensions!

print(str({(lambda n : ((n*(3*n -1))/2))(x) for x in range(1000000)} &  {(lambda n : ((n*(2*n -1))))(x) for x in range(1000000)}))

This only uses 2 checks since all hexagonal numbers are also triangular, so really we’re only looking for the next pentagonal number that is also hexagonal. Each lambda in the set comprehension is pentagonal or hexagonal numbers. We build a very large set, then find the intersection of those sets. Awesome.

Done! :-D