Advertisement
rdrewd

problem14_nico.py

May 27th, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. """
  2. Longest Collatz sequence
  3. ------------------------
  4.  
  5. The following iterative sequence is defined for the set of positive integers:
  6. n  n/2 (n is even)
  7. n  3n + 1 (n is odd)
  8. Using the rule above and starting with 13, we generate the following sequence:
  9. 13  40  20  10  5  16  8  4  2  1
  10. It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
  11. Which starting number, under one million, produces the longest chain?
  12. NOTE: Once the chain starts the terms are allowed to go above one million.
  13.  
  14. Approach:
  15.  
  16. A function `collatz` which returns the number of terms in the chain, given it's starting position.
  17. It goes trough the sequence, but It also remembers previous ones using a global dictionary.
  18. Get the maximum one.
  19. """
  20.  
  21. collatz_counts = {}
  22.  
  23. def collatz(n):
  24.     count = 1
  25.     start = n
  26.     while n!=1:
  27.         if n in collatz_counts:
  28.             count += collatz_counts[n]
  29.             break
  30.         if n%2==0: n/=2
  31.         else: n = 3*n+1
  32.         count += 1
  33.  
  34.     collatz_counts[start] = count
  35.     return count
  36.  
  37. answer = max(((collatz(i),i) for i in range(1,1000000)))
  38. print("The starting position generating the longest sequence is",answer[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement