From b56f368d3cdcb166d740725ad26d488ccce445e5 Mon Sep 17 00:00:00 2001 From: Correl Roush Date: Wed, 5 May 2010 04:45:16 +0000 Subject: [PATCH] Problem 045 git-svn-id: file:///srv/svn/euler@71 e5f4c3ec-3c0c-11df-b522-21efaa4426b5 --- e045.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 e045.py diff --git a/e045.py b/e045.py new file mode 100644 index 0000000..5d3a9c4 --- /dev/null +++ b/e045.py @@ -0,0 +1,54 @@ +"""After 40755, what is the next triangle number that is also pentagonal and 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. +""" + +def triangle_generator(start = 0): + n = start + while True: + n = n + 1 + yield n * (n + 1) / 2 +def pentagonal_generator(start = 0): + n = start + while True: + n = n + 1 + yield n * (3 * n - 1) / 2 +def hexagonal_generator(start = 0): + n = start + while True: + n = n + 1 + yield n * (2 * n - 1) + +MIN = 40755 + +def main(): + pent_count = 0 + tri_count = 0 + for hex in hexagonal_generator(): + if hex <= MIN: + continue + # Catch up the other generators + for pent in pentagonal_generator(pent_count): + pent_count = pent_count + 1 + if pent >= hex: + break + if pent > hex: + continue + for tri in triangle_generator(tri_count): + tri_count = tri_count + 1 + if tri >= hex: + break + if tri > hex: + continue + print 'Next number is:', hex + break +if __name__ == '__main__': + main() \ No newline at end of file