Posted By

chroto on 05/21/10


Tagged


Versions (?)

Project Euler - Problem 14


 / Published in: Python
 

  1. #!/usr/bin/python
  2.  
  3. # Project Euler - Problem 14
  4. import math
  5. print "\nProject Euler - Problem 14"
  6. print "For the sequence: \n"
  7. print "n -> n/2 (if n is even)"
  8. print "n -> 3n+1 (if n is odd)\n"
  9. print "Find the longest chain that ends in '1'"
  10.  
  11. start = 10**6
  12. num = (start/2)
  13. ans = 0
  14. maxcnt=0
  15. while num < start:
  16. x = num
  17. cnt = 1
  18. while x != 1:
  19. if x & 1: x = 3*x + 1 # odd
  20. else: x >>= 1 # even
  21. cnt += 1
  22. if cnt > maxcnt:
  23. ans = num
  24. maxcnt = cnt
  25. num += 1
  26. print ans

Report this snippet  

You need to login to post a comment.