Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. # Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are:
  2. #
  3. # 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
  4. #
  5. # It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.
  6. #
  7. # Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and
  8. # D = |Pk − Pj| is minimised; what is the value of D?
  9.  
  10.  
  11. from math import sqrt
  12.  
  13.  
  14. def is_pentagonal(n):
  15. if n < 1:
  16. return 0
  17. k = (1 + sqrt(1 + 24 * n)) / 6
  18. if k == int(k):
  19. return int(k)
  20. return 0
  21.  
  22.  
  23. pentagonals = dict()
  24.  
  25.  
  26. def pentagonal(n):
  27. global pentagonals
  28. if n in pentagonals:
  29. return pentagonals[n]
  30. p = int(n * (3 * n - 1) / 2)
  31. pentagonals[n] = p
  32. return p
  33.  
  34.  
  35. def main():
  36. a = 1
  37. results = []
  38. while a < 3000:
  39. # Ugly empirical upper bound
  40. # No guarantee that the difference is indeed minimal but the solution is correct, so oh well
  41. pa = pentagonal(a)
  42. b = 1
  43. while b < a:
  44. pb = pentagonal(b)
  45. if is_pentagonal(pa - pb) and is_pentagonal(pa + pb):
  46. print(b, a, pa - pb)
  47. results.append([b, a, pa - pb, pb, pa, pa + pb])
  48. b += 1
  49. a += 1
  50. return results
  51.  
  52.  
  53. print(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement