Guest User

Untitled

a guest
Jun 21st, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1.  
  2. from math import sqrt
  3.  
  4. sum1to = __import__("001 - sum multiples of 3 and 5").sum1to
  5. factorize = __import__("003 - largest prime factor of composite").factorize
  6.  
  7. def num_factors(n):
  8. """num_factors(int) -> int
  9.  
  10. Return the number of factors (prime or not) for a given number.
  11. """
  12. factors = factorize(n)
  13. num = 1
  14. for x, exp in factors:
  15. num *= (exp+1)
  16. return num
  17.  
  18. def triangle_with_min_num_factors_slow(min_num_factors):
  19. i = 1
  20. factor_count = 1
  21. num = 1
  22.  
  23. while factor_count < min_num_factors:
  24. i = i+1
  25. num = sum1to(i)
  26. factor_count = num_factors(num)
  27. else:
  28. triangle_number = sum1to(i)
  29. return i, num, factor_count
  30.  
  31. return 0, 0, 0
  32.  
  33. def triangle_with_min_num_factors_slower(min_num_factors):
  34. i = 0
  35. num = 0
  36.  
  37. while True:
  38. i = i+1
  39. num += i
  40. num_factors = 0
  41.  
  42. n = 1
  43. root = int(round(sqrt(num)))
  44.  
  45. while n <= root:
  46. if (num % n) is 0:
  47. num_factors += 2
  48. n += 1
  49.  
  50. if num_factors >= min_num_factors:
  51. return i, num, num_factors
  52.  
  53. return 0, 0, 0
  54.  
  55. if __name__ == "__main__":
  56. num, triangle, num_factors = triangle_with_min_num_factors_slow(500)
  57.  
  58. print """First triangle number with >= 500 factors is triangle(%d)=%d
  59. %d has %d factors.""" % (num, triangle, triangle, num_factors)
Add Comment
Please, Sign In to add comment