Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. """
  2. Question 2:
  3.  
  4. If n is even, process it as n/2
  5. If n is odd, process it as 3n + 1
  6.  
  7. Find the number of steps required for a number to get to 1.
  8.  
  9. Example: 3 -> 10 -> 5-> 16 -> 8 -> 4 -> 2 -> 1
  10. Output = 7 steps
  11.  
  12. Find the number with the highest number of steps under 1 million.
  13. """
  14.  
  15.  
  16.  
  17.  
  18. # Map to save te number of steps for a given number. We don't want to re-calculate it again and again, so we cache in this map.
  19. d = {}
  20.  
  21.  
  22. def get_steps(i):
  23. # If result is in map, return directly
  24. if i in d:
  25. return d[i]
  26.  
  27. # Base case
  28. if i == 1:
  29. return 0
  30.  
  31. # Calculate the steps using recurrence relation.
  32. # E.g.
  33. # steps(3) = steps(10) + 1
  34. # steps(10) = steps(5) + 1
  35. if i%2 == 0:
  36. t = i / 2
  37. else:
  38. t = (3 * i) + 1
  39.  
  40. d[i] = get_steps(t) + 1 # Cache it in map before returning
  41.  
  42. return d[i]
  43.  
  44.  
  45. def find_max():
  46. max_i = None
  47. max_steps = 0
  48. for i in range(2, 1000001):
  49. t = get_steps(i)
  50. if t > max_steps:
  51. max_steps = t
  52. max_i = i
  53. return max_steps, max_i
  54.  
  55. #print(get_steps(3))
  56. print(find_max())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement