Advertisement
banovski

Project Euler, Problem #12, Python

Feb 26th, 2022 (edited)
747
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. # The sequence of triangle numbers is generated by adding the natural
  2. # numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 +
  3. # 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36,
  4. # 45, 55, ... Let us list the factors of the first seven triangle
  5. # numbers: 1: 1; 3: 1, 3; 6: 1, 2, 3, 6; 10: 1, 2, 5, 10; 15: 1, 3, 5,
  6. # 15; 21: 1, 3, 7, 21; 28: 1, 2, 4, 7, 14, 28 We can see that 28 is
  7. # the first triangle number to have over five divisors. What is the
  8. # value of the first triangle number to have over five hundred
  9. # divisors?
  10.  
  11. # Version 1: slightly shorter and faster
  12.  
  13. cntr = 2
  14. ctn = 1
  15. dn = 0
  16.  
  17. while True:
  18.     ctn += cntr
  19.     md = int(ctn ** 0.5)
  20.     if md < ctn ** 0.5:
  21.         cv = 0
  22.     else:
  23.         cv = 1
  24.  
  25.     if ctn % 2 == 0:
  26.         dn = sum([2 if ctn % x == 0 else 0 for x in range(1, md + 1)])
  27.  
  28.     else:
  29.         dn = sum([2 if ctn % x == 0 else 0 for x in range(1, md + 1, 2)])
  30.  
  31.     if dn - cv > 500:
  32.         break
  33.     dn = 0
  34.     cntr += 1
  35.  
  36. print(ctn)
  37.  
  38. # 76576500
  39. # 24752 function calls in 9.839 seconds
  40.  
  41. # Version 2
  42.  
  43. cntr = 2
  44. ctn = 1
  45. dn = 0
  46.  
  47. while True:
  48.     ctn += cntr
  49.     md = int(ctn ** 0.5)
  50.     if md < ctn ** 0.5:
  51.         cv = 0
  52.     else:
  53.         cv = 1
  54.  
  55.     if ctn % 2 == 0:
  56.         for d in range(1, md + 1):
  57.             if ctn % d == 0:
  58.                 dn += 2
  59.     else:
  60.         for d in range(1, md + 1, 2):
  61.             if ctn % d == 0:
  62.                 dn += 2
  63.  
  64.     if dn - cv > 500:
  65.         break
  66.     dn = 0
  67.     cntr += 1
  68.  
  69. print(ctn)
  70.  
  71. # 76576500
  72. # 12376 function calls in 10.944 seconds
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement