// you’re reading...

Project Euler Solutions

Project Euler Problem 45 Solution

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Problem Description

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.

Analysis

Note that Hexagonal numbers are a subset of Triangle numbers so we only determine the first occurrence of Hi = Pj to find our answer. We can safely start our search from 166 as eluded to in the problem’s description.

From our experience with problem 44 we were able to make our search trivial without the use of arrays.

Solution

Runs < 1 second in Python.

from math import sqrt
 
def is_pentagonal(n):
  p = ( sqrt(1 + 24*n) + 1 ) / 6
  return p==int(p)
 
n = 165 
while True:
  n += 1 
  hex = n * (2 * n-1)
  if is_pentagonal(hex): break 
 
print "Answer to PE45 = ",hex

Comments

See Problem 44.
The next number in the series is 57722156241751, calculated in about 15 seconds.

Discussion

2 comments for “Project Euler Problem 45 Solution”

  1. Note that Hexagonal numbers are a subset of Triangle numbers …

    It is the other way around! And aren’t you supposed to start with n=143 instead of n=165 ?
    15seconds? What device are you running your code on?

    Posted by YePkE | January 19, 2010, 10:26 am
  2. OK. The first 10 triangle numbers are {1, 3, 6, 10, 15, 21, 28, 36, 45, 55} and the first 10 hexagonal numbers are {1, 6, 15, 28, 45, 66, 91, 120, 153, 190}. Every hexagonal number is a triangular number not the other way around. In fact a hexagonal number is every second triangle number making hexagonal numbers a subset of triangle numbers.

    The example in the problem shows us the n=165 meets the criteria so we can safely start at this ‘n’ to find the next number.

    This problem is solved on a P4/2GHz.

    Thanks for your comment and I hope this answers your questions.

    Posted by Mike | January 19, 2010, 6:36 pm

Post a comment