princeofsudan

ProjectEuler#45 Triangular, pentagonal, and hexagonal

Mar 28th, 2013
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.15 KB | None | 0 0
  1. #Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
  2. #Triangle       Tn=n(n+1)/2      1, 3, 6, 10, 15, ...
  3. #Pentagonal     Pn=n(3n-1)/2     1, 5, 12, 22, 35, ...
  4. #Hexagonal      Hn=n(2n-1)       1, 6, 15, 28, 45, ...
  5.  
  6. #It can be verified that T285 = P165 = H143 = 40755.
  7.  
  8. #Find the next triangle number that is also pentagonal and hexagonal.
  9.  
  10. #Every hexagonal number is a triangular number.
  11. #One can efficiently test whether a positive integer x is an hexagonal number by computing:
  12. #n=(sqrt(8x+1)+1)/4
  13. #If n is an integer, then x is the nth hexagonal number.
  14. #So. 40755 is the H143 number
  15. #Source: http://en.wikipedia.org/wiki/Hexagonal_number
  16. #One can efficiently test whether a positive integer x is an pentagonal number by computing:
  17. #n=(sqrt(24x+1)+1)/6
  18. #If n is an integer, then x is the nth pentagonal number.
  19. #So. 40755 is P165
  20. #Source: http://en.wikipedia.org/wiki/Pentagonal_number
  21.  
  22. def isPentagonal(n):
  23.     if (((24*n+1)**0.5)+1)%6 == 0:
  24.         return True
  25.     else:
  26.         return False
  27.  
  28. n = 144
  29. while True:
  30.     hexagon = n*(2*n-1)
  31.     if isPentagonal(hexagon):
  32.         print hexagon
  33.         break
  34.     n += 1
Advertisement
Add Comment
Please, Sign In to add comment