princeofsudan

Project Euler#14 Longest Collatz sequence

Mar 4th, 2013
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. #The following iterative sequence is defined for the set of positive integers:
  2.  
  3. #n → n/2 (n is even)
  4. #n → 3n + 1 (n is odd)
  5.  
  6. #Using the rule above and starting with 13, we generate the following sequence:
  7. #13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
  8.  
  9. #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.
  10.  
  11. #Which starting number, under one million, produces the longest chain?
  12.  
  13. #NOTE: Once the chain starts the terms are allowed to go above one million.
  14.  
  15. def isEven(n):
  16.     if n%2 == 0:
  17.         return True
  18.     else:
  19.         return False
  20.  
  21. def isOdd(n):
  22.     if n%2 == 0:
  23.         return False
  24.     else:
  25.         return True
  26.  
  27.  
  28. maxChain = 0
  29. maxStart = 0
  30.  
  31. for i in range(2,1000000):
  32.     n = i
  33.     count = 1
  34.    
  35.  
  36.     while n != 1:
  37.         if isEven(n):
  38.             n = n/2
  39.             count += 1
  40.            
  41.         else:
  42.             n = (3*n) + 1
  43.             count += 1
  44.            
  45.  
  46.     if count > maxChain:
  47.         maxChain = count
  48.         maxStart = i
  49.  
  50. print maxChain,maxStart
  51.  
  52. #Improvement (Not implemented): only check odd n. it was proved empirically that the chain length of odd starting numbers was always equal to or larger than the previous even starting number.
Advertisement
Add Comment
Please, Sign In to add comment