Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. from time import time, sleep
  2.  
  3. #my fastest version up to now
  4. def proper_divisors_sum1(n):
  5.     pd_list = []
  6.     for x in range(1, int(n**.5)+1):
  7.         if n % x == 0:
  8.             pd_list.append(x)
  9.             pd_list.append(n//x)
  10.     pd_list = list(set(pd_list))
  11.     pd_list.sort()
  12.     pd_list = pd_list[:-1]
  13.     return sum(pd_list)
  14.  
  15.  
  16. #This uses several of Martin's ideas
  17. #It's now my fastest version
  18. def proper_divisors_sum2(n):
  19.     pd = set((1,))
  20.     for x in range(2, int(n**.5)+1):
  21.         if n % x == 0:
  22.             pd.update((x, n//x))
  23.     return sum(list(pd))
  24.  
  25.  
  26. # This incorporates all of Martin's ideas
  27. # Seems that divmod() is a speed killer
  28. def proper_divisors_sum3(n):
  29.     pd = set((1,))
  30.     for x in range(2, int(n**.5)+1):
  31.         factor, mod = divmod(n,x)
  32.         if mod == 0:
  33.             pd.update((x,factor))
  34.     return sum(list(pd))
  35.  
  36.  
  37. n = 100000
  38. m = 100000  #number of loops
  39. sleep_secs = 1
  40.  
  41.  
  42. t0 = time()
  43. for i in range(m):
  44.     sum_ = proper_divisors_sum1(n)
  45. t1 = time()
  46. print("time1 =", round((t1-t0), 3))
  47.  
  48. sleep(sleep_secs)
  49.  
  50. t0 = time()
  51. for i in range(m):
  52.     sum_ = proper_divisors_sum2(n)
  53. t1 = time()
  54. print("time2 =", round((t1-t0), 3))
  55.  
  56. sleep(sleep_secs)
  57.  
  58. t0 = time()
  59. for i in range(m):
  60.     sum_ = proper_divisors_sum3(n)
  61. t1 = time()
  62. print("time3 =", round((t1-t0), 3))
  63.  
  64. """
  65. time1 = 8.999
  66. time2 = 7.924
  67. time3 = 13.959
  68. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement