princeofsudan

ProjectEuler#44 Pentagon numbers

Apr 7th, 2013
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. #Pentagonal numbers are generated by the formula, Pn=n(3n-1)/2.
  2. #The first ten pentagonal numbers are:
  3.  
  4. #1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
  5.  
  6. #It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However,
  7. #their difference, 70 - 22 = 48, is not pentagonal.
  8.  
  9. #Find the pair of pentagonal numbers, Pj and Pk, for which their sum and
  10. #difference are pentagonal and D = |Pk - Pj| is minimised;
  11. #what is the value of D?
  12.  
  13. import time
  14.  
  15. def pentagonal(n):
  16.     if n >= 1:
  17.         return (n * (3 * n - 1) )/2
  18.  
  19. def isPentagonal(n):
  20.     if (((24*n+1)**0.5)+1)%6 == 0:
  21.         return True
  22.     else:
  23.         return False
  24.  
  25. start = time.time()
  26.  
  27. pentagonals = []
  28. n = 0
  29. flag = True
  30. while flag:
  31.     n += 1
  32.     newPentagonal = pentagonal(n)
  33.     pentagonals.append(newPentagonal)
  34.     for i in pentagonals:
  35.         if isPentagonal(newPentagonal - i)\
  36.            and isPentagonal(newPentagonal + i):
  37.             print newPentagonal - i
  38.             flag = False
  39.            
  40. end = time.time()
  41. print end - start
Advertisement
Add Comment
Please, Sign In to add comment